<?php

namespace Home\Controller;

require './vendor/autoload.php';
use PHPThumb\GD;

use Home\Org\Util\Sqlserver;
use Home\Org\Util\SQLSERVERDATASINGLETON;
//use function Sodium\add;
use Think\Controller;
use Think\Model;

use Home\Model\AuthModel;

use Org\Util\UploadFile;

use Home\Org\Util\ProductManager;

use Home\Org\Util\UserRole;
use Home\Org\Util\PermissionDatabase;

require './vendor/autoload.php';
use Intervention\Image\ImageManager;
use Intervention\Image\ImageManagerStatic as Image;

/**
 * 供应商引入
 * @author dem
 *
 */
class SapSupplierController extends HomeController {
    
    private $userlist = array(); //array('dem','Mario','william.li');//可审核人列表

    private function checkPermission(){

        //get operator by db
        $modelSupplierOperator = D("supplier_operator");
        $filed = ('*');
        $operatorList = $modelSupplierOperator->field($filed)->select();
        foreach ($operatorList as $key => $value){
            $userlist[] = $value['emp_no'];
            $operator[$value['emp_no']] = $value['type'];
        }
        $this->userlist = $userlist;

        $user = session('user_name');
        if (in_array($user, $this->userlist))
        {
            //权限类型，默认0发起人，1审批人
            if ($operator[$user] == 1)
            {
                // 确认是审核人
                return TRUE;
            }
            return FALSE;
        }
        return FALSE;

    }

    private function checkItemEditorPermission(){

        //get operator by db
        $modelItemEditorOperator = D("item_editor_operator");
        $filed = ('*');
        $operatorList = $modelItemEditorOperator->field($filed)->select();
        foreach ($operatorList as $key => $value){
            $userlist[] = $value['emp_no'];
            $operator[$value['emp_no']] = $value['type'];
        }

        $user = session('user_name');
        if (in_array($user, $userlist))
        {
            //权限类型，默认0普通修改，1高级修改
            if ($operator[$user] == 1)
            {
                // 确认高级修改
                return TRUE;
            }
            return TRUE;
        }
        return FALSE;

    }

    function index(){

        //本参数用于控制申请/审批按钮的显示
        $showBtn =  I('showbtn'); //$_REQUEST['showbtn'];

        //get operator by db
        $modelSupplierOperator = D("supplier_operator");
        $filed = ('*');
        $operatorList = $modelSupplierOperator->field($filed)->select();
        foreach ($operatorList as $key => $value){
            $userlist[] = $value['emp_no'];
            $operator[$value['emp_no']] = $value['type'];
        }
        $this->userlist = $userlist;

        $user = session('user_name');
        if (in_array($user, $this->userlist))
        {
            //权限类型，默认0发起人，1审批人
            $this->assign('operatorType',$operator[$user]);
        }

        //如果有供应商ID则通知VIEW层展示
        $supplierID = I('supplierID');
        $supplierName = I('supplierName');
        $this->assign('supplierID',$supplierID);
        $this->assign('supplierName',$supplierName);

        $this->assign('showbtn',$showBtn);
        $this->assign('access',in_array($user, $this->userlist));
        $this->display();

    }

    /**
     * 2017-11-01
     * 品牌 -> 产品经理
     */
    function getpmbybrandname20171101(){
        $this->display();
    }

    function getpmbybrandname20171101data(){

        // html
        $brandName = I('c_name');

        // sap data
        $productManagerMappingBrandModel = M('productManagerMappingBrand');
        $data = $productManagerMappingBrandModel->where("brand_name like '%".$brandName."%'")->select();

        // oa data
        $sapBrandModel = M('sapBrand');
        $oaData = $sapBrandModel->where("examine_status = 1 AND b_name like '%".$brandName."%'")->select();

        //$oaData = array(array('brand_name'=>$brandName));
        foreach ($oaData as $key => $item)
        {
            $item['brand_name'] = $item['b_name'];
            $item['product_manager_name'] = $item['recommender'];
            if($item['product_manager_name']) {
                array_push($data, $item);
            }
        }

        echo json_encode(array('total'=>1,'data'=>$data));exit;

    }

    function getpmbybrandname20171101excel(){

        // html
        $brandName = I('c_name');

        // sap data
        $productManagerMappingBrandModel = M('productManagerMappingBrand');
        $data = $productManagerMappingBrandModel->where("brand_name like '%".$brandName."%'")->select();

        // oa data
        $sapBrandModel = M('sapBrand');
        $oaData = $sapBrandModel->where("examine_status = 1 AND b_name like '%".$brandName."%'")->select();

        //$oaData = array(array('brand_name'=>$brandName));
        foreach ($oaData as $key => $item)
        {
            $item['brand_name'] = $item['b_name'];
            $item['product_manager_name'] = $item['recommender'];
            if($item['product_manager_name']) {
                array_push($data, $item);
            }
        }

        //Export to Excel:
        Vendor('Excel.PHPExcel');
        $objPHPExcel = new \PHPExcel();
        $currentSheet = $objPHPExcel->getSheet(0);
        $m = 1;
        $currentSheet->setCellValue('A'.$m, '产品经理');
        $currentSheet->setCellValue('B'.$m, '品牌');

        $cellIndex = 1;
        foreach ($data as $key => $value){
            $cellIndex++;
            $currentSheet->setCellValueExplicit('A'.$cellIndex,$value['product_manager_name'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('B'.$cellIndex,$value['brand_name'], \PHPExcel_Cell_DataType::TYPE_STRING);
        }

        $name = uniqid().'.xls';
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $name );
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;

    }

    /**
     * 2017-11-01
     * 产品经理 -> 品牌
     */
    function getbrandbypmname20171101(){
        $this->display();
    }

    function getbrandbypmname20171101data(){

        // html
        $pmName = I('pm_name');

        // sap data
        $productManagerMappingBrandModel = M('productManagerMappingBrand');
        $data = $productManagerMappingBrandModel->where("product_manager_name like '%".$pmName."%'")->select();

        // oa data
        $sapBrandModel = M('sapBrand');
        $oaData = $sapBrandModel->where("examine_status = 1 AND recommender like '%".$pmName."%'")->select();

        //$oaData = array(array('product_manager_name'=>$pmName));
        foreach ($oaData as $key => $item)
        {
            $item['brand_name'] = $item['b_name'];
            $item['product_manager_name'] = $item['recommender'];
            array_push($data,$item);
        }
        echo json_encode(array('total'=>1,'data'=>$data));exit;
    }

    function getbrandbypmname20171101excel(){

        // html
        $pmName = I('pm_name');

        // sap data
        $productManagerMappingBrandModel = M('productManagerMappingBrand');
        $data = $productManagerMappingBrandModel->where("product_manager_name like '%".$pmName."%'")->select();

        // oa data
        $sapBrandModel = M('sapBrand');
        $oaData = $sapBrandModel->where("examine_status = 1 AND recommender like '%".$pmName."%'")->select();

        //$oaData = array(array('product_manager_name'=>$pmName));
        foreach ($oaData as $key => $item)
        {
            $item['brand_name'] = $item['b_name'];
            $item['product_manager_name'] = $item['recommender'];
            array_push($data,$item);
        }

        //Export to Excel:
        Vendor('Excel.PHPExcel');
        $objPHPExcel = new \PHPExcel();
        $currentSheet = $objPHPExcel->getSheet(0);
        $m = 1;
        $currentSheet->setCellValue('A'.$m, '产品经理');
        $currentSheet->setCellValue('B'.$m, '品牌');

        $cellIndex = 1;
        foreach ($data as $key => $value){
            $cellIndex++;
            $currentSheet->setCellValueExplicit('A'.$cellIndex,$value['product_manager_name'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('B'.$cellIndex,$value['brand_name'], \PHPExcel_Cell_DataType::TYPE_STRING);
        }

        $name = uniqid().'.xls';
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $name );
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;

    }
    
    
    /**
     * 品牌列表
     */
    function brandlist(){
        $this->display();
    }

    function getBrandListDataAll(){
        $c_name = I('c_name');

        $model =M('SapBrand');
        $pageIndex = I('pageIndex');//?intval(I('pageIndex'))-1:0;
        $pageSize = I('pageSize')?:50;
        $where='1 = 1 ';
        if($c_name) {$where.=" AND b_name like '%{$c_name}%' ";}

        $total =$model->where($where)->order("b_id desc")->count();
        $res = $model->where($where)->order("b_id desc")->limit($pageIndex*$pageSize,$pageSize)->select();
        echo json_encode(array('total'=>$total,'data'=>$res));exit;

    }
    
    function getBrandListData(){
        $c_name = I('c_name');
        
        $model =M('SapBrand');
        $pageIndex = I('pageIndex');//?intval(I('pageIndex'))-1:0;
        $pageSize = I('pageSize')?:50;
        $where='1 = 1 ';
        if($c_name) {$where.=" AND b_name like '%{$c_name}%' AND examine_status = 1";}
        else{
            $where.= " AND examine_status = 1";
        }
        $total =$model->where($where)->order("b_id desc")->count();
        $res = $model->where($where)->order("b_id desc")->limit($pageIndex*$pageSize,$pageSize)->select();
        echo json_encode(array('total'=>$total,'data'=>$res));exit;
        
    }
    
    /**
     * 新增 编辑 品牌
     */
    function brandadd(){
        
        $plugin['date'] = true;
        $plugin['uploader'] = true;
        $plugin['editor'] = true;
        $plugin['auth'] = true;
        $this->assign('filepath','/Uploads/Download/SapSupplier/'.date('Y-m').'/');
        $this -> assign("plugin", $plugin);
        
        $this->display();
        
    }
    
    function brandedit(){
        $id = intval(I('id'));
        if($id){
            $data = M('SapBrand')->where('b_id='.$id)->find();
            $attarr = explode(';', $data['attachment']);//附件
             
            $filemodel = M('File');
            $attlist = array();
            foreach ($attarr as $key=>$att){
                if(!$att)continue;
                $file_id = think_decrypt($att);
                $attlist[$key]=$filemodel->where("id={$file_id}")->find();
                $attlist[$key]['code']=$att;
                $attlist[$key]['size']= ceil($attlist[$key]['size']/1000);
            }
            $data['att']=$attlist;

            // for category_code
            //$categories = explode(",", $data['category_code']);
            //$this->assign('firstCategory',$categories[0]);

            $this->assign('data',$data);

            $plugin['date'] = true;
            $plugin['uploader'] = true;
            $plugin['editor'] = true;
            $plugin['auth'] = true;
            $this->assign('filepath','/Uploads/Download/SapSupplier/'.date('Y-m').'/');
            $this -> assign("plugin", $plugin);

            //check permission
            if ($this->checkPermission()){
                // has permission,go progress then.
                $this->assign('haspermission',TRUE);
            }else{
                // has not permission.
                $this->assign('haspermission',FALSE);
            }

            $this->display('brandadd');
            
        }
    }
    
    function brandselect(){
        $this->display();
    }
    
    
    function dobrandadd(){
        $respone = array('code'=>0,'msg'=>'保存成功');
        $saveData = json_decode($_POST['data'],true);
        $date = date('Y-m-d H:i:s');
        if(!$saveData){
            $respone['code']=-1;
            $respone['msg']='参数错误';
            echo json_encode($respone);exit;
        }
        $m = D('SapBrand');
        try {
            $id = $saveData['id'];
            unset($saveData['id']);
            if($id){
                 // do update

                $authID = session('auth_id');
                $check = $m->where('b_id='.$id)->find();
                if ($check['operatorid'] == $authID) {
                    $saveData['utime'] = $date;
                    $saveData['examine_status']  = 0;
                    $saveData['status'] = 'U';
                    $res = $m->where("b_id={$id}")->save($saveData);

                    //2017-08-18 修改时添加备注
                    $remarkes = $saveData['remarkes'];
                    $info = "发起申请";
                    $info = $remarkes?$info.",备注:".$remarkes:$info;
                    $logModel =M('SapBrandLog');
                    $logModel->add(array('pid'=>$id,'user'=>session('user_name'),'info'=>$info,'ctime'=>date('Y-m-d H:i:s'),'type'=>__FUNCTION__));

                }

            }else{
                //do save

                $saveData['operatorid'] = session('auth_id');
                $saveData['operatorname'] = session('emp_no');

                $saveData['examine_status']  = 0;
                $saveData['status']  = 'A';

                $saveData['ctime'] = $date;
                $saveData['utime'] = $date;
                $res =  $m->add($saveData);

                //2017-08-18 创建时添加备注
                $remarkes = $saveData['remarkes'];
                $info = "发起申请";
                $info = $remarkes?$info.",备注:".$remarkes:$info;
                $logModel =M('SapBrandLog');
                $logModel->add(array('pid'=>$res,'user'=>session('user_name'),'info'=>$info,'ctime'=>date('Y-m-d H:i:s'),'type'=>__FUNCTION__));
               
            }

            //TODO: 发送邮件微信
            //$receiver = "maxwell.shi";
            // 2017-08-23 将 mario 的权限 移交给 wendy.li
            $receiver = "wendy.li";
            $operator = session('emp_no');
            $this->sendEmail($receiver.'@g-town.com.cn', "品牌:{$saveData['b_name']},信息变更", "品牌:{$saveData['b_name']},信息变更<br/>操作人:{$operator}");
            //weixinsendmsg("品牌:{$saveData['b_name']},信息变更", "品牌:{$saveData['b_name']},信息变更\n操作人:{$operator}",$operator);

        }catch (\Exception $e){
            $respone['code']=-1;
            $respone['msg']=$e->getMessage();
            echo json_encode($respone);exit;
        }
        
        if(!$res){
            $respone['code']=-1;
            $respone['msg']=$m->getError();
        }
        
        echo json_encode($respone);exit;
        
    }
    
    /**
     * 供应商列表
     */
    function supplierlist(){
        $this->display();
    }

    function getAllSuppliers()
    {
        $model = M('SapSupplier');
        $filed = "id, name as text";
        $where = '1 = 1 ';
        //$where .= " AND examine_status = 1 ";

        $total =$model->where($where)->order("id desc")->count();
        $res = $model->field($filed)->where($where)->order("id desc")->select();

        echo json_encode($res,JSON_UNESCAPED_UNICODE); exit;
    }
    
    function getSupplierListData()
    {
        $c_name = I('c_name');
        $eq_type = I('eq_type');

        $model = M('SapSupplier');
        $pageIndex = I('pageIndex'); //? intval(I('pageIndex')) - 1 : 0;
        $pageSize = I('pageSize') ?: 50;
        //echo $pageIndex;
        $where = '1 = 1 ';
        if ($c_name) $where .= " AND name like '%{$c_name}%' ";

        if ($eq_type == 'all') {
        } else {


            if (!empty($eq_type)) {
                $where .= " AND examine_status = " . $eq_type . " ";
            } elseif ($eq_type == 0) {
                $where .= " AND examine_status = " . $eq_type . " ";
            }

        }

        //TODO:和当前用户绑定

        $operatorName = session("emp_no");
        $operator =  session('auth_id');

        $modelSupplierOperator = D("supplier_operator");
        $result = $modelSupplierOperator->where("emp_no='$operatorName'")->find();

        //if($result)
        if(1) {

            if ($result['type'] == 1) {
                // 审批人
            } else {
                // 发起人
                //$where .= " AND operatorid = " . $operator . " ";
            }

            $total = $model->where($where)->order("id desc")->count();
            $res = $model->where($where)->order("id desc")->limit($pageIndex * $pageSize, $pageSize)->select();

            echo json_encode(array('total' => $total, 'data' => $res));
            exit;

        }else{
            exit;
        }
    
    }
    
    /**
     * 新增  编辑供应商
     */
    function supplieradd(){

        $plugin['date'] = true;
        $plugin['uploader'] = true;
        $plugin['editor'] = true;
        $plugin['auth'] = true;
        $this->assign('filepath','/Uploads/Download/supplier/'.date('Y-m').'/');
        $this -> assign("plugin", $plugin);
        $this->display();

    }
    
    
    function supplieredit(){

        $id = intval(I('id'));
        if($id){
            $data = M('SapSupplier')->where('id='.$id)->find();

            $attarr = explode(';', $data['attachment']);//附件
            $filemodel = M('File');
            $attlist = array();
            foreach ($attarr as $key=>$att){
                if(!$att)continue;
                $file_id = think_decrypt($att);
                $attlist[$key]=$filemodel->where("id={$file_id}")->find();
                $attlist[$key]['code']=$att;
                $attlist[$key]['size']= ceil($attlist[$key]['size']/1000);
            }
            $data['att']=$attlist;

            //check operatorid
            $authID = session('auth_id');
            if ($data['operatorid'] == $authID)
            {
                // can edit
                $this->assign('canedit',TRUE);
            }else{
                // can not
                $this->assign('canedit',FALSE);
            }

            //check permission
            if ($this->checkPermission()){
                // has permission,go progress then.
                $this->assign('haspermission',TRUE);
                // can edit
                $this->assign('canedit',TRUE);
            }else{
                // has not permission.
                $this->assign('haspermission',FALSE);
            }

            $this->assign('data',$data);

            //upload file
            $plugin['date'] = true;
            $plugin['uploader'] = true;
            $plugin['editor'] = true;
            $plugin['auth'] = true;
            $this->assign('filepath','/Uploads/Download/supplier/'.date('Y-m').'/');
            $this -> assign("plugin", $plugin);
        
            $this->display('supplieredit');
        
        }
        
    }
    
    function dosupplieradd(){

        $respone = array('code'=>0,'msg'=>'保存成功');
        $saveData = json_decode($_POST['data'],true);
        $date = date('Y-m-d H:i:s');
        if(!$saveData){
            $respone['code']=-1;
            $respone['msg']='参数错误';
            echo json_encode($respone);exit;
        }
        $m = D('SapSupplier');
        try {
            $id = $saveData['id'];
            unset($saveData['id']);
            if($id){
                // do update
                $saveData['utime'] = $date;
                $saveData['status']  = 'U';
                $saveData['examine_status'] = 0;
                $res =  $m->where("id={$id}")-> save($saveData);
            }else{
                //do save
                 
                $saveData['status']  = 'A';
                $saveData['utime'] = $date;
                $saveData['ctime'] = $date;

                $saveData['operatorid'] = session('auth_id');
                $saveData['operatorname'] = session('emp_no');

                $res =  $m->add($saveData);
                if($res){
                    M('sapSplIntroduce')->add(array('s_id'=>$res,'s_name'=>$saveData['name'],'ctime'=>date('Y-m-d H:i:s'),'status'=>0));
                }

                //2017-08-18 创建时添加备注
                $remarkes = $saveData['remarkes'];
                $info = "发起申请";
                $info = $remarkes?$info.",备注:".$remarkes:$info;
                $logModel =M('SapSplLog');
                $logModel->add(array('pid'=>$res,'user'=>session('user_name'),'info'=>$info,'ctime'=>date('Y-m-d H:i:s'),'type'=>__FUNCTION__));
                 
            }

            //TODO: 发送邮件微信
            //$receiver = "maxwell.shi";
            // 2017-08-23 将 mario 的权限 移交给 wendy.li
            $receiver = "wendy.li";
            $operator = session('emp_no');
            $this->sendEmail($receiver.'@g-town.com.cn', "供应商:{$saveData['name']},信息变更", "供应商:{$saveData['name']},信息变更<br/>操作人:{$operator}");
            //weixinsendmsg("供应商:{$saveData['name']},信息变更", "供应商:{$saveData['name']},信息变更\n操作人:{$operator}",$operator);

        }catch (\Exception $e){
            $respone['code']=-1;
            $respone['msg']=$e->getMessage();
            echo json_encode($respone);exit;
        }
        
        if(!$res){
            $respone['code']=-1;
            $respone['msg']=$m->getError();
        }
        
        echo json_encode($respone);exit;
        
        
    }
    
    /**
     * 物料列表
     */
    function itemlist(){
        $this->display();
    }
    
    
    function getItemListData(){

        $c_name = I('c_name');
        $model =M('SapItems');
        $pageIndex = I('pageIndex');//?intval(I('pageIndex'))-1:0;
        $pageSize = I('pageSize')?:50;
        $where='1 = 1 ';
        if($c_name) $where.=" AND item_name like '%{$c_name}%' ";
        $total =$model->where($where)->order("sap_code desc")->count();
        $res = $model->where($where)->order("sap_code desc")->limit($pageIndex*$pageSize,$pageSize)->select();
        echo json_encode(array('total'=>$total,'data'=>$res));exit;
        
    }

    function importitembyexcel(){
        $this->display();
    }

    function doimportitembyexcel()
    {
        //$time =time();
        $today = date("Y-m-d H:i:s");
        $time = $today;
        // excel 表头 与 mysql 表头对应关系
        $orderHeadArray = array(

            '物料简名' =>'item_short_name', //A
            '颜色' =>'color', //B
            '型号'=>'model', //C
            '规格'=>'specifications', //D
            '品牌(SAP系统内已有品牌）'=>'brand_name', //E - 需要找出 brand_id
            '品类(SAP系统内已有品类）'=>'category_code', //F - 需要转换为 code
            '重量'=>'weight', //G
            '订货周期'=>'ordering_day', //H
            '是否序列号管理'=>'is_serial', //I
            '产品经理'=>'pm', //J
            '采购价格'=>'OriginalPurchasePrice',//K
            'sap物料编号(非必填)' => 'sap_code', //L
            '备注'=>'remarkes', //M

        );


        if (!empty($_FILES)) {
            import("@.ORG.UploadFile");
            $config = array(
                'allowExts' => array('xlsx', 'xls'),
                'savePath' => './exceltojh/',
                'saveRule' => 'time',
            );
            $upload = new UploadFile($config);
            if (!$upload->upload($config['savePath'])) {
                $this->error($upload->getErrorMsg());
            } else {

                $info = $upload->getUploadFileInfo();
                $theType = $info[0]['type'];
                if($theType != "application/vnd.ms-excel" && $theType != "application/octet-stream")
                {
                    $this->assign('errorInfo',"文件类型错误！");
                    $this->display();
                    return;
                }

                $name = $info[0]['savename'];
                Vendor('Excel.PHPExcel');
                $filename= $config['savePath'].$name;

                $objPHPExcel = \PHPExcel_IOFactory::load($filename);

                $sheetData   = $objPHPExcel -> getActiveSheet() -> toArray(null, true, true, true);

                $currentSheet = $objPHPExcel->getSheet(0);
                $allColumn = $currentSheet->getHighestColumn();//取到最大列数
                $allRow = $currentSheet->getHighestRow();//取到最大行数

                // excel 中表头
                $excelHeadCN = $sheetData[1];
                $excelHead = array();
                foreach ($excelHeadCN as $key => $value) {
                    $excelHead[$key] = $orderHeadArray[$value];
                }
                unset($excelHead['']);
                foreach ($excelHead as $key => $value) {
                    if (empty($value)) {
                        unset($excelHead[$key]);
                    }
                }
                // Table表头与Excel列对应关系
                //var_dump($excelHead);
                unset($sheetData[1]); //删除excel表头 列名等行数据

                $mergeStr = '';
                $countNum = 0;
                foreach ($sheetData as $key => $v) {
                    //数据 $key行号 $v数组

                    $targetData = array();
                    foreach ($v as $inkey => $value) {
                        //Core
                        $targetData[$excelHead[$inkey]] = trim($value);
                    }
                    unset($targetData['']);

                    // 补全数据
                    $targetData['status'] = 'A'; //物料状态 U需要更新sap, A需要新增到sap, N无需操作
                    $targetData['ctime'] = $time;
                    $targetData['utime'] = $time;
                    $targetData['UptodatePurchasePrice'] = $targetData['OriginalPurchasePrice'];

                    // brand_id, OA table:think_sap_brand 根据 brand_name 查询 找到继续, 找不到停止报错
                    $theBrandName = addslashes($targetData['brand_name']);
                    $model = M('SapBrand');
                    $where = '1 = 1 ';
                    $where .= " AND b_name = '" . $theBrandName . "' ";
                    $res = $model->where($where)->find();
                    if ($res['b_id']) {
                        //echo "the brand id is: ".$res['b_id'];
                        $targetData['brand_id'] = $res['b_id'];
                    } else {
                        $this->assign('errorInfo',"行: ".$key."品牌信息错误,导入失败！");
                        $this->display();
                        exit();
                    }

                    // pm,验证pm的正确性：比对表 think_product_manager 中内容
                    import("@.ORG.Util.ProductManager");
                    $productManager = ProductManager::getInstance();
                    $productManagerList = $productManager->getProductManagerList();
                    $targetData['pm'] = strtolower($targetData['pm']);
                    if(!in_array($targetData['pm'],$productManagerList))
                    {
                        $this->assign('errorInfo',"行: ".$key."产品经理信息错误,导入失败！");
                        $this->display();
                        exit();
                    }

                    // category_code, SAP table: [@TI_Z0151] 根据 code_name 查询 找到继续, 找不到停止报错
                    $getCategoryCode = 0;
                    import("@.ORG.Util.SQLSERVERDATASINGLETON");
                    $sqlSERVERDATASINGLETON  = SQLSERVERDATASINGLETON::getInstance();
                    $categories = $sqlSERVERDATASINGLETON->getDataTIZ0151();
                    foreach ($categories as $inkey => $value){
                        if ( $value['text'] == $targetData['category_code']){
                            $targetData['category_code'] = $value['id'];
                            //print_r($value);
                            if ($value['is3C'] == '3C')
                            {
                                $targetData['is_3c'] = 'Y';
                            }else{
                                $targetData['is_3c'] = 'N';
                            }
                            $getCategoryCode = 1;
                            break;
                        }
                    }
                    if ($getCategoryCode){
                    }else{
                        $this->assign('errorInfo',"行: ".$key."品类信息错误,导入失败！");
                        $this->display();
                        exit();
                    }

                    $emp_no = session('emp_no');
                    $targetData['emp_no'] = $emp_no;

                    // 2017-07-25 mergedString
                    $targetData['item_name'] = $targetData['brand_name'].' '.$targetData['item_short_name'].' '.$targetData['model'].' '.$targetData['specifications'].' '.$targetData['color'];

                    $str = "'" . implode("','", $targetData) . "'";

                    $countNum++;

                    if ($countNum == 1) $mergeStr .= "({$str})";
                    else $mergeStr .= ", ({$str})";

                }
                $sql = " insert into think_sap_items  (" . implode(',', array_keys($targetData)) . ") values $mergeStr";
                //echo $sql;die();

                $sapbankRelationModel = M('sapbankRelation');
                $result = $sapbankRelationModel->execute($sql);
                $return = 0;
                $errorStr = '导入不成功！';
                if ($result) {
                    $return = 1;
                    $errorStr = '导入成功！';
                }
                //echo json_encode(array('data' => $return, 'msg' => $errorStr), 1);

                $this->assign('errorInfo',$errorStr);
                $this->display();

            }
        }
    }

    /**
     * 新增 编辑物料
     */
    function itemadd(){

        $plugin['date'] = true;
        $plugin['uploader'] = true;
        $plugin['editor'] = true;
        $plugin['auth'] = true;
        $this->assign('filepath','/Uploads/Download/goods/'.date('Y-m').'/');
        $this -> assign("plugin", $plugin);

        $this->display();
    }

    function plainCategory($key,$result)
    {
        import("@.ORG.Util.SQLSERVERDATASINGLETON");
        $sqlSERVERDATASINGLETON  = SQLSERVERDATASINGLETON::getInstance();
        $categories = $sqlSERVERDATASINGLETON->getDataTIZ0151();

        foreach ($categories as $inkey => $value){

            if($value['id'] == $key)
            {
                //var_dump($value);die();
                if ($value['pid'])
                {
                    // continue
                    $result[] = $value;
                    return $this->plainCategory($value['pid'],$result);
                }else{
                    $result[] = $value;
                    return $result;
                }
            }

        }

    }

    function itemshow(){

        $id = intval(I('id'));
        if($id){

            //$data = M('SapItems')->where('item_id='.$id)->find();
            $quersql = "SELECT  *,b.id as attachmentID from  think_sap_items as a LEFT JOIN think_sap_item_attachment as b on a.item_id=b.oa_id WHERE a.item_id =".$id;
            $qResult =  M('SapItems')->query($quersql);
            if(is_array($qResult)) {
                $data = $qResult[0];
            }else
            {
                return;
            }

            $attarr = explode(';', $data['attachment']);//附件
            $filemodel = M('File');
            $attlist = array();
            foreach ($attarr as $key=>$att){
                if(!$att)continue;
                $file_id = think_decrypt($att);
                $attlist[$key]=$filemodel->where("id={$file_id}")->find();
                $attlist[$key]['code']=$att;
                $attlist[$key]['size']= ceil($attlist[$key]['size']/1000);
            }
            $data['att']=$attlist;

            // 2017-08-07 添加图片关联表
            $sapItemsImageModel = M("sapItemsImage");
            $imageResult = $sapItemsImageModel->where("oa_item_id = {$data['item_id']}")->select();
            if ($imageResult){
                $data['hasImageResult'] = 1;
                $data['imageResult'] = $imageResult;
            }else{
                $data['hasImageResult'] = 0;
            }

            //var_dump($data);die();

            $this->assign('data',$data);

            $plainCategories = array();
            $myCategories = $this->plainCategory($data['category_code'],$plainCategories);
            sort($myCategories);
            $categories = '';
            foreach ($myCategories as $key => $value)
            {
                $categories .= $value[text]." / ";
            }

            $this->assign('categories',$categories);
            $this->display('itemshow');

        }
    }

    function resizeimg()
    {
        $id = intval(I('id'));
        $width = intval(I('width'));
        $height = intval(I('height'));
        $imgid = intval(I('imgid'));

        if ($width <= 700 && $width > 0 && $height <= 700 && $height > 0) {
            if ($id) {
                $data = M('SapItems')->where('item_id=' . $id)->find();
                $logo = explode(',', $data['logo']);

                $imageURL = $logo[$imgid];
                $check = strrchr($imageURL, ':');

                if ($check === FALSE && $imageURL) {
                    $imageURL = WWWROOT . $logo[$imgid];
                } else {
                }
                if ($imageURL)
                    $this->generateResizeImage($imageURL, $width, $height);
            }
        }else{
            echo "参数错误！";
        }
    }

    function resizedetailimg()
    {
        $id = intval(I('id'));
        $width = intval(I('width'));
        $height = intval(I('height'));
        $imgid = intval(I('imgid'));

        if ($width <= 700 && $width > 0 && $height <= 700 && $height > 0) {
            if ($id) {
                $data = M('SapItems')->where('item_id=' . $id)->find();
                $logo = explode(',', $data['detail_image']);

                $imageURL = $logo[$imgid];
                $check = strrchr($imageURL, ':');

                if ($check === FALSE && $imageURL) {
                    $imageURL = WWWROOT . $logo[$imgid];
                } else {
                }
                if ($imageURL)
                    $this->generateResizeImage($imageURL, $width, $height);
            }
        }else{
            echo "参数错误！";
        }
    }

    function generateResizeImage($imageURL, $maxWidth,$maxHeight)
    {
        $thumb = new GD($imageURL);
        $thumb->resize($maxWidth, $maxHeight)->show();
    }
    
    function itemedit(){

        $id = intval(I('id'));
        if($id){

            $plugin['date'] = true;
            $plugin['uploader'] = true;
            $plugin['editor'] = true;
            $plugin['auth'] = true;
            $this->assign('filepath','/Uploads/Download/goods/'.date('Y-m').'/');
            $this -> assign("plugin", $plugin);

            //$data = M('SapItems')->where('item_id='.$id)->find();
            $quersql = "SELECT  *,b.id as attachmentID from  think_sap_items as a LEFT JOIN think_sap_item_attachment as b on a.item_id=b.oa_id WHERE a.item_id =".$id;
            $qResult =  M('SapItems')->query($quersql);
            if(is_array($qResult)) {
                $data = $qResult[0];
            }else
            {
                return;
            }

            $attarr = explode(';', $data['attachment']);//附件
            $filemodel = M('File');
            $attlist = array();
            foreach ($attarr as $key=>$att){
                if(!$att)continue;
                $file_id = think_decrypt($att);
                $attlist[$key]=$filemodel->where("id={$file_id}")->find();
                $attlist[$key]['code']=$att;
                $attlist[$key]['size']= ceil($attlist[$key]['size']/1000);
            }
            $data['att']=$attlist;

            // 2017-08-07 添加图片关联表
            $sapItemsImageModel = M("sapItemsImage");
            $imageResult = $sapItemsImageModel->where("oa_item_id = {$data['item_id']}")->select();
            if ($imageResult){
                $data['hasImageResult'] = 1;
                $data['imageResult'] = $imageResult;
            }else{
                $data['hasImageResult'] = 0;
            }

            //var_dump($data);die();

            $this->assign('data',$data);

            if($data['check_modify']==1) {
                if ($this->checkItemEditorPermission()) {
                    $this->assign('canEdit', TRUE);
                }
            }else{
                $this->assign('canEdit', TRUE);
            }
        
            $this->display('itemedit');
        
        }

    }

    function getitemcategorycode(){

        import("@.ORG.Util.Sqlserver");
        $sqlObj  = new Sqlserver();
        $where = '';
//      $key = iconv('utf-8', 'GBK', $key);
        $sql = "select U_nodecode,U_fahercode,U_nodename,U_is3C from [@TI_Z0151]";
        $res = $sqlObj->query($sql);
        $tree = array();
        foreach ($res as $key => $value)
        {
            // $key : 0, 1, 2, 3,
            // $value : array with key
            if ($value['U_fahercode']){
                $tree[] = array ('id'=>$value['U_nodecode'],'text'=>$value['U_nodename'],'pid'=>$value['U_fahercode'],'is3C'=>$value['U_is3C']);
            }else{
                $tree[] = array ('id'=>$value['U_nodecode'],'text'=>$value['U_nodename'],'checked'=>'true','is3C'=>$value['U_is3C']);
            }
        }
        //$data = array('total'=>count($res),'data'=>$res);
        echo json_encode($tree);
        exit;

    }

    function getitemcategorycodeOnlyLevelTwo(){

        import("@.ORG.Util.Sqlserver");
        $sqlObj  = new Sqlserver();
        $where = '';
//      $key = iconv('utf-8', 'GBK', $key);
        $sql = "select U_nodecode,U_fahercode,U_nodename,U_is3C from [@TI_Z0151]";
        $res = $sqlObj->query($sql);
        $tree = array();
        $root = array();
        // root
        foreach ($res as $key => $value)
        {
            // $key : 0, 1, 2, 3,
            // $value : array with key
            if ($value['U_fahercode']){
            }else{
                $root[] = array ('id'=>$value['U_nodecode'],'text'=>$value['U_nodename'],'checked'=>'true','is3C'=>$value['U_is3C']);
            }
        }
        // second level
        foreach ($root as $k => $v){
            foreach ($res as $key => $value){
                if ($value['U_fahercode'] == $v['id'])
                {
                    $tree[] = array ('id'=>$value['U_nodecode'],'text'=>$value['U_nodename'],'pid'=>$value['U_fahercode'],'is3C'=>$value['U_is3C']);
                }
            }
            $tree[] = $v;
        }

        //$tree = $root;

        //$data = array('total'=>count($res),'data'=>$res);
        echo json_encode($tree);
        exit;

    }

    function doitemadd(){

        $respone = array('code'=>0,'msg'=>'保存成功');
        $saveData = json_decode($_POST['data'],true);

        $date = date('Y-m-d H:i:s');
        $emp_no = session('emp_no');

        if(!$saveData){
            $respone['code']=-1;
            $respone['msg']='参数错误';
            echo json_encode($respone);exit;
        }
        $m = D('SapItems');
        try {
            $id = $saveData['id'];
            unset($saveData['id']);
            if($id){

                    // do update

                // brand_id, OA table:think_sap_brand 根据 brand_name 查询 找到继续, 找不到停止报错
                $theBrandName = addslashes($saveData['brand_name']);
                $model = M('SapBrand');
                $where = '1 = 1 ';
                $where .= " AND b_name = '" . $theBrandName . "' ";
                $res = $model->where($where)->find();
                if ($res['b_id']) {
                } else {
                    $respone['code']=-1;
                    $respone['msg']= "品牌信息错误，更新失败！";
                    echo json_encode($respone);exit;
                }

                    // 物料主信息
                    $saveData['utime'] = $date;
                    $saveData['status'] = 'U';
                    $saveData['OriginalPurchasePrice'] = $saveData['UptodatePurchasePrice'];
                    $res = $m->where("item_id={$id}")->save($saveData);

                    // 物料附加信息
                    $sapItemAttachment = M("sapItemAttachment");
                    // 1. 之前没有 - 创建
                    if(empty($saveData['attachmentID']))
                    {

                        $saveData['oa_id'] = $id;
                        $saveData['updatetime'] = $date;
                        $saveData['emp_no'] = $emp_no;
                        $result = $sapItemAttachment->add($saveData);

                    }
                    // 2. 已存在 - 更新
                    else{
                        $saveData['updatetime'] = $date;
                        $saveData['emp_no'] = $emp_no;
                        $result = $sapItemAttachment->where("id={$saveData['attachmentID']}")->save($saveData);
                    }

            }else{

                $theItemName = addslashes($saveData['item_name']);
                // 检测物料名称是否重复
                $check = $m->where("item_name='{$theItemName}'")->find();
                if($check){
                    // 有同名数据
                    $respone['code']=-1;
                    $respone['msg']="物料名已存在";
                    echo json_encode($respone);exit;

                }else {
                    // do save

                    // brand_id, OA table:think_sap_brand 根据 brand_name 查询 找到继续, 找不到停止报错
                    $model = M('SapBrand');
                    $where = '1 = 1 ';
                    $theBrandName = addslashes($saveData['brand_name']);
                    $where .= " AND b_name = '" . $theBrandName . "' ";
                    $res = $model->where($where)->find();
                    if ($res['b_id']) {
                    } else {
                        $respone['code']=-1;
                        $respone['msg']= "品牌信息错误，创建失败！";
                        echo json_encode($respone);exit;
                    }

                    // 物料主信息
                    $saveData['status'] = 'A';
                    $saveData['utime'] = $date;
                    $saveData['ctime'] = $date;
                    $saveData['OriginalPurchasePrice'] = $saveData['UptodatePurchasePrice'];
                    $saveData['emp_no'] = $emp_no;
                    $res = $m->add($saveData);

                    // 物料附加信息
                    $sapItemAttachment = M("sapItemAttachment");
                    $saveData['oa_id'] = $res;
                    $saveData['updatetime'] = $date;
                    $saveData['emp_no'] = $emp_no;
                    $result = $sapItemAttachment->add($saveData);
                }

            }
        }catch (\Exception $e){
            $respone['code']=-1;
            $respone['msg']=$e->getMessage();
            echo json_encode($respone);exit;
        }
        
        if(!$res){
            $respone['code']=-1;
            $respone['msg']=$m->getError();
        }
        
        echo json_encode($respone);exit;
        
        
    }
    
    function upload() {
        $this -> _upload();
    }
    
    function getauthData(){
        $id = I('id');
        if(!$id)exit;
        $idlist = M('SapSplIntroduce')->where("s_id={$id}")->find();
        if(!$idlist){
            echo json_encode(array('total'=>0,'data'=>array()));exit;
        }
        
      
        $model =M('Auth');
        $pageIndex = I('pageIndex')?intval(I('pageIndex'))-1:0;
        $pageSize = I('pageSize')?:20;
        $where="spl_id ={$id}  AND is_delete=0 ";
        $total =$model->where($where)->count();
        $res = $model->where($where)->limit($pageIndex*$pageSize,$pageSize)->select();
        foreach ($res as $key=>$vo){
            $res[$key]['status']=$this->_getstatus($res[$key]['end']);
            $res[$key]['code'] = str_replace(',', '<br/>',  $res[$key]['code']);
            $res[$key]['cname'] = str_replace(',', '<br/>',  $res[$key]['cname']);
            $res[$key]['start']=date('Y-m-d', $res[$key]['start']);
            $res[$key]['end']=date('Y-m-d', $res[$key]['end']);
            $res[$key]['ctime']=date('Y-m-d', $res[$key]['ctime']);
        }
        echo json_encode(array('total'=>$total,'data'=>$res));exit;
    }
    
    function _getstatus($end){
        $return = "<span style='color:green'>正常</span>";
        if($end<time()){
            $return = "<span style='color:red'>失效</span>";
        }
        return $return;
    }
    

    
    function deleteauth(){
        //$respones = array('code'=>'0','msg'=>'操作成功');
        //$splid = intval(I('splid'));
        $authId = intval(I('authid'));
        $model = M('Auth');
        $res =$model->where("id={$authId}")->save(array('is_delete'=>1));
       if(!$res){
           $respones['code']=-1;
           $respones['msg'] = $model->getError();
       }
        echo json_encode($respones);exit;
    }
    
    /**
     * 毛利
     */
    function updatesupplierprofit(){
        $model = M('SapSupplierProfit');
        $data = json_decode($_POST['data'],true);
        if(isset($data['id'])&&$data['id']){
            //update
             $id= $data['id'];
             unset($data['id']);
             $data['examine_status']=0;
            echo  $model->where("id={$id}")->save($data);
        }else{

            // 只有当 examine_status 的值不等于1时,更新状态。
            $sapSupplierModel = M('SapSupplier');
            $supplierItem = $sapSupplierModel->where("id={$data['sid']}")->find();
            if ($supplierItem['examine_status'] != 1) {
                $sapSupplierModel->where("id={$data['sid']}")->save(array('examine_status' => 0));
            }
            echo  $model->add($data);
        }
      
        
    }

    function getitemprofitBeforeSale(){

        $itemId = $_REQUEST['item_id'];
        if (empty($itemId)){}
        else {
            $model = M('ItemProfitBeforeSale');
            $field = '*';
            $result = $model->field($field)->where("item_id={$itemId}")->order("ctime desc")->select();
            $jsonData = json_encode($result);
            echo $jsonData;exit;
        }

    }

    function updateitemprofitBeforeSale(){
        $model = M('itemProfitBeforeSale');
        $data = json_decode($_POST['data'],true);
        $time = date('Y-m-d H:i:s');

        foreach ($data as $key => $dataValue){
            if ($dataValue['_state'] == 'added' && $dataValue['Customer_Code'] && $dataValue['profit_name']){
                $dataValue['ctime'] = $time;
                $dataValue['utime'] = $time;

                //check profit_name + item_id + Customer_Code
                $where = "profit_name = '".$dataValue['profit_name']."' and Customer_Code = '".$dataValue['Customer_Code']."' and item_id = '".$dataValue['item_id']."'";
                $check = $model->where($where)->find();
                if($check){}
                else {
                    echo $model->add($dataValue);
                }
            }

            if ($dataValue['_state'] == 'modified' && $dataValue['Customer_Code'] && $dataValue['profit_name']){
                $where="Customer_Code='{$dataValue['Customer_Code']}' AND item_id='{$dataValue['item_id']}' AND id='{$dataValue['id']}' ";
                $dataValue['utime'] = $time;
                echo  $model->where($where)->save($dataValue);
            }
        }

    }

    
    function getSapSupplierProfitListData(){
        $sid = I('id');
        if(!$sid) exit;
        $model =M('SapSupplierProfit');
        $pageIndex = I('pageIndex')?intval(I('pageIndex'))-1:0;
        $pageSize = I('pageSize')?:20;
        $where="sid={$sid} AND is_delete=0 ";
        $total =$model->where($where)->count();
        $res = $model->where($where)->order('examine_status ')->limit($pageIndex*$pageSize,$pageSize)->select();
        echo json_encode(array('total'=>$total,'data'=>$res));exit;
        
    }

    public function review20170527(){

        //供应商ID
        $s_id   = intval(I('id'));
        //审批类型
        $status = intval(I('status'));
        //审批记录表
        $logModel =M('SapSplLog');

        //供应商表
        $sapSupplierModel = M('SapSupplier');
        //更新供应商状态
        $sapSupplierModel->where("id={$s_id}")->save(array('examine_status'=>$status));

        //记录审批历史
        $remarkes = I('remarkes');
        if ($status == 0){
            $info = "发起申请";
        }else {
            $info = $status == 1 ? "审核通过" : "审核未通过";
        }
        $info = $remarkes?$info.",备注:".$remarkes:$info;
        $logModel->add(array('pid'=>$s_id,'user'=>session('user_name'),'info'=>$info,'ctime'=>date('Y-m-d H:i:s'),'type'=>__FUNCTION__));

        //返回数据
        echo 1;exit;
    }

    /**
     * 审核毛利
     */
    public function review(){

        //供应商ID
        $s_id   = intval(I('id'));
        //审批类型
        $status = intval(I('status'));
        //物料表
        $profitModel = M('sapSupplierProfit');
        //审批记录表
        $logModel =M('SapSplLog');
        //授权表
        $authModel   = M('Auth');

        //更新物料状态
        $profitModel->where("sid={$s_id} and examine_status=0 ")->save(array('examine_status'=>$status));
        //更新授权状态
        $authModel->where("spl_id={$s_id} and examine_status=0 ")->save(array('examine_status'=>$status));

        //供应商表
        $sapSupplierModel = M('SapSupplier');
        //更新供应商状态
        $sapSupplierModel->where("id={$s_id}")->save(array('examine_status'=>$status));

        //记录审批历史
        $remarkes = I('remarkes');
        if ($status == 0){
            $info = "发起申请";
        }else {
            $info = $status == 1 ? "审核通过" : "审核未通过";
        }
        $info = $remarkes?$info.",备注:".$remarkes:$info;
        $logModel->add(array('pid'=>$s_id,'user'=>session('user_name'),'info'=>$info,'ctime'=>date('Y-m-d H:i:s'),'type'=>__FUNCTION__));

        //拼接数据
        if ($status == 1) {
            $supplier = $sapSupplierModel->where("id={$s_id}")->find();
            $items = $profitModel->where("sid={$s_id}")->select();
            $authes = $authModel->where("spl_id={$s_id}")->select();

            $returnData = array();
            $returnData['supplier'] = $supplier;
            $returnData['items'] = $items;
            $returnData['authes'] = $authes;
            $jsonData = json_encode($returnData);
        }

        //返回数据
        echo 1;exit;
    }

    public function supplierstatecheck()
    {
        $this->assign('src', 'SapSupplier/supplierstatecheckiframe');
        $this->display();
    }

    function getlog(){
        $s_id   = intval(I('id'));
        $logModel =M('SapSplLog');
        $data = $logModel->where("pid={$s_id}")->order("id desc")->select();
        echo json_encode($data);
        exit;
    }
    
    /**
     * 删除毛利数据
     */
    function deleteprofit(){

        $respones = array('code'=>'0','msg'=>'操作成功');
        $pid = intval(I('id'));
        $model = M('sapSupplierProfit');
        $res =$model->where("id={$pid}")->save(array('is_delete'=>1));
        if(!$res){
            $respones['code']=-1;
            $respones['msg'] = $model->getError();
        }
        echo json_encode($respones);exit;

    }

    public function review20170706(){

        //供应商ID
        $b_id   = intval(I('id'));
        //审批类型
        $status = intval(I('status'));
        //审批记录表
        $logModel =M('SapBrandLog');

        //供应商表
        $sapBrandModel = M('SapBrand');
        //更新供应商状态
        $sapBrandModel->where("b_id={$b_id}")->save(array('examine_status'=>$status));

        //记录审批历史
        $remarkes = I('remarkes');
        if ($status == 0){
            $info = "发起申请";
        }else {
            $info = $status == 1 ? "审核通过" : "审核未通过";
        }
        $info = $remarkes?$info.",备注:".$remarkes:$info;
        $logModel->add(array('pid'=>$b_id,'user'=>session('user_name'),'info'=>$info,'ctime'=>date('Y-m-d H:i:s'),'type'=>__FUNCTION__));

        //返回数据
        echo 1;exit;
    }

    function getbrandlog(){
        $s_id   = intval(I('id'));
        $logModel =M('SapBrandLog');
        $data = $logModel->where("pid={$s_id}")->order("id desc")->select();
        echo json_encode($data);
        exit;
    }

    function canceldoc(){
        $respone = array('code'=>0,'msg'=>'已将文件标记为作废');

        $fileID = I('id');
        $fileModel = M('File');
        $saveData = array();
        $saveData['cancelled'] = 1;
        $result = $fileModel->where("id={$fileID}")->save($saveData);

        if($result){
            echo json_encode($respone);
            exit;
        }
    }

    function cancelimage(){

        $respone = array('code'=>0,'msg'=>'已将图片标记为作废');

        $itemId = I('item_id');
        $imageId = I('image_id');
        $imageType = I('image_type');

        //var_dump($itemId.$imageId,$imageType);die();

        $sapItemsImageModel = M("sapItemsImage");

        $saveData = array();
        $saveData['oa_item_id'] = $itemId;
        $saveData['image_id'] = $imageId;
        $saveData['image_type'] = $imageType;
        $saveData['cancelled'] = 1;

        $result = $sapItemsImageModel->add($saveData);

        if($result){
            echo json_encode($respone);
            exit;
        }

    }

    public function updatesapitembyexcel()
    {
        $this->display();
    }

    public function doimportupdatesapitembyexcel()
    {
        $tag =time();
        $today = date("Y-m-d H:i:s");
        $time = $today;
        // excel 表头 与 mysql 表头对应关系
        $orderHeadArray = array(

            '物料号' =>'sap_code', //A
            '产品经理' =>'pm', //B
            '物料名称' =>'item_name', //C

        );

        if (!empty($_FILES)) {
            import("@.ORG.UploadFile");
            $config = array(
                'allowExts' => array('xlsx', 'xls'),
                'savePath' => './exceltojh/',
                'saveRule' => 'time',
            );
            $upload = new UploadFile($config);
            if (!$upload->upload($config['savePath'])) {
                $this->error($upload->getErrorMsg());
            } else {

                $info = $upload->getUploadFileInfo();
                $theType = $info[0]['type'];
                //echo $theType;die();
                if($theType != "application/vnd.ms-excel" && $theType != "application/octet-stream")
                {
                    $this->assign('errorInfo',"文件类型错误！");
                    $this->display();
                    return;
                }

                $name = $info[0]['savename'];
                Vendor('Excel.PHPExcel');
                $filename= $config['savePath'].$name;

                $objPHPExcel = \PHPExcel_IOFactory::load($filename);

                $sheetData   = $objPHPExcel -> getActiveSheet() -> toArray(null, true, true, true);

                $currentSheet = $objPHPExcel->getSheet(0);
                $allColumn = $currentSheet->getHighestColumn();//取到最大列数
                $allRow = $currentSheet->getHighestRow();//取到最大行数

                // excel 中表头
                $excelHeadCN = $sheetData[1];
                $excelHead = array();
                foreach ($excelHeadCN as $key => $value) {
                    $excelHead[$key] = $orderHeadArray[$value];
                }
                unset($excelHead['']);
                foreach ($excelHead as $key => $value) {
                    if (empty($value)) {
                        unset($excelHead[$key]);
                    }
                }
                // Table表头与Excel列对应关系
                //var_dump($excelHead);
                unset($sheetData[1]); //删除excel表头 列名等行数据

                $mergeStr = '';
                $countNum = 0;
                foreach ($sheetData as $key => $v) {
                    //数据 $key行号 $v数组

                    $targetData = array();
                    foreach ($v as $inkey => $value) {
                        //Core
                        $targetData[$excelHead[$inkey]] = trim($value);
                    }
                    unset($targetData['']);

                    $targetData['item_name'] = addslashes($targetData['item_name']);

                    // 补全数据
                    $targetData['list_tag'] = $tag;
                    $targetData['status'] = 'NEW'; //NEW:Excel新导入, UPDATE:已更新物料主数据, REJECT
                    $targetData['ctime'] = $time;
                    $targetData['utime'] = $time;
                    $targetData['upload_emp_no'] = session('emp_no');

                    $str = "'" . implode("','", $targetData) . "'";

                    $countNum++;

                    if ($countNum == 1) $mergeStr .= "({$str})";
                    else $mergeStr .= ", ({$str})";

                }
                $sql = " insert into think_update_sap_items  (" . implode(',', array_keys($targetData)) . ") values $mergeStr";
                //echo $sql;die();

                $sapbankRelationModel = M('sapbankRelation');
                $result = $sapbankRelationModel->execute($sql);
                $return = 0;
                $errorStr = '导入不成功！';
                if ($result) {
                    $return = 1;
                    $errorStr = '导入成功！';
                }
                //echo json_encode(array('data' => $return, 'msg' => $errorStr), 1);

                $this->assign('errorInfo',$errorStr);
                $this->display();

            }
        }
    }

    public function listupdatesapitemfromexcel()
    {
        $this->display();
    }

    public function getlistupdatesapitemfromexcel()
    {
        $model =M('updateSapItems');
        $pageIndex = I('pageIndex');
        $pageSize = I('pageSize')?:50;
        $where='1 = 1 ';
        $all =$model->where($where)->group("list_tag")->order("id desc")->select();
        $total = count($all);
        $res = $model->where($where)->group("list_tag")->order("id desc")->limit($pageIndex*$pageSize,$pageSize)->select();
        echo json_encode(array('total'=>$total,'data'=>$res));exit;

    }

    public function showupdatesapitemlist()
    {
        $listTag = I('list_tag');
        $this->assign('listTag',$listTag);
        $this->display();
    }

    public function showupdatesapitemlistdetail()
    {
        $model =M('updateSapItems');
        $pageIndex = I('pageIndex');
        $pageSize = I('pageSize')?:50;
        $listTag = I('list_tag');
        $where="1 = 1 AND list_tag = '{$listTag}'";
        $total =$model->where($where)->order("id desc")->count();
        $res = $model->where($where)->order("id desc")->limit($pageIndex*$pageSize,$pageSize)->select();
        echo json_encode(array('total'=>$total,'data'=>$res));exit;
    }

    public function doupdatesapitemfromexcel(){

        $respone = array('code'=>0,'msg'=>'成功');

        $listTag = I('list_tag');
        $approve = I('approve');
        //var_dump($listTag.'='.$approve);die();

        $date = date('Y-m-d H:i:s');
        $operator = session('emp_no');
        $updateSapItemsModel = M('updateSapItems');

        // 权限控制 Table: think_supplier_operator
        $supplierOperatorModel = M('supplierOperator');
        $checkPermmission = $supplierOperatorModel->where("emp_no = '{$operator}'")->find();

        if($checkPermmission['id']){

            if ($approve) {

                //update

                // check NEW
                $check = $updateSapItemsModel->where("list_tag = '{$listTag}'")->find();
                if ($check['status'] == 'NEW' || $check['status'] == 'UPDATE') {
                    $toUpdateData = $updateSapItemsModel->where("list_tag = '{$listTag}'")->select();

                    $sapItemsModel = M("sapItems");
                    foreach ($toUpdateData as $key => $value) {
                        $saveData['pm'] = $value['pm'];
                        $saveData['status'] = 'U';
                        $sapItemsModel->where("sap_code = '{$value['sap_code']}'")->save($saveData);
                    }

                    $updateSapItemsModel->where("list_tag = '{$listTag}'")->save(array('status' => 'UPDATE', 'utime' => $date, 'exe_emp_no' => $operator));
                } else {
                    $respone = array('code' => 0, 'msg' => '不能重复执行刷新操作！');
                }

            } else {

                //reject

                // check NEW
                $check = $updateSapItemsModel->where("list_tag = '{$listTag}'")->find();
                if ($check['status'] == 'NEW') {
                    $updateSapItemsModel->where("list_tag = '{$listTag}'")->save(array('status' => 'REJECT', 'utime' => $date, 'exe_emp_no' => $operator));
                } else {
                    $respone = array('code' => 0, 'msg' => '不能重复执行刷新操作！');
                }

            }

        }else{
            $respone = array('code' => 0, 'msg' => '没有权限执行此操作！');
        }

        echo json_encode($respone);
        exit;

    }

    /**
     * 2017-08-29
     * 导出物料 远丰格式 Excel
     */
    function exportskuyuanfeng(){

        $this->display();

    }

    /**
     * 2017-08-29
     * 导出物料 远丰格式 Excel
     */
    function doexportskuyuanfeng(){

        $skuArray = array(
            'B10000016',
            'B10000017',
            'B10000018',
            'B10000019',
            'B10000020',

            'B10000021',
            'B10000022',
            'B10000023',
            'B10000024',
            'B10000025',

            'B10000001',
            'B10000002',
            'B10000003',
            'B10000004',
            'B10000005',
            'B10000006',
            'B10000007',
            'B10000008',
            'B10000009',
            'B10000010',
        );
        $data = array();

        if(1)
        {
            $sapItemsModel = M('sapItems');

            foreach ($skuArray as $skuKey => $skuValue) {
                $quersql = "SELECT * from think_sap_items WHERE sap_code = '{$skuValue}'";
                $singleData = $sapItemsModel->query($quersql);
                if (is_array($singleData)) {
                    $data[] = $singleData[0];
                }
            }
            //var_dump($data);die();

            //Export to Excel:
            Vendor('Excel.PHPExcel');
            $objPHPExcel = new \PHPExcel();
            $currentSheet = $objPHPExcel->getSheet(0);
            $m = 1;
            $currentSheet->setCellValue('A'.$m, '商品名称');
            $currentSheet->setCellValue('B'.$m, '商品英文名称');
            $currentSheet->setCellValue('C'.$m, '市场价格');
            $currentSheet->setCellValue('D'.$m, '销售价格');
            $currentSheet->setCellValue('E'.$m, '库存数量');

            $currentSheet->setCellValue('F'.$m, '商品主图');
            $currentSheet->setCellValue('G'.$m, '温馨提示');
            $currentSheet->setCellValue('H'.$m, '英文温馨提示');
            $currentSheet->setCellValue('I'.$m, '商品类型（0全新/1二手）');
            $currentSheet->setCellValue('J'.$m, '商品描述');

            $currentSheet->setCellValue('K'.$m, 'SKU');
            $currentSheet->setCellValue('L'.$m, '商品详情图1');
            $currentSheet->setCellValue('M'.$m, '商品详情图2');
            $currentSheet->setCellValue('N'.$m, '商品详情图3');
            $currentSheet->setCellValue('O'.$m, '有无发票（0无/1有）');

            $cellIndex = 1;
            foreach ($data as $key => $value){
                $cellIndex++;
                $currentSheet->setCellValueExplicit('A'.$cellIndex,$value['item_name'], \PHPExcel_Cell_DataType::TYPE_STRING);
                $currentSheet->setCellValueExplicit('B'.$cellIndex,'', \PHPExcel_Cell_DataType::TYPE_STRING);
                $currentSheet->setCellValueExplicit('C'.$cellIndex,'', \PHPExcel_Cell_DataType::TYPE_STRING);
                $currentSheet->setCellValueExplicit('D'.$cellIndex,'', \PHPExcel_Cell_DataType::TYPE_STRING);
                $currentSheet->setCellValueExplicit('E'.$cellIndex,'',\PHPExcel_Cell_DataType::TYPE_STRING);

                $currentSheet->setCellValueExplicit('F'.$cellIndex,"https://www.gt-mall.cn/uploadfile/product/".$value['sap_code']."/".$value['sap_code']."_01.jpg",\PHPExcel_Cell_DataType::TYPE_STRING);
                $currentSheet->setCellValueExplicit('G'.$cellIndex,'', \PHPExcel_Cell_DataType::TYPE_STRING);
                $currentSheet->setCellValueExplicit('H'.$cellIndex,'',\PHPExcel_Cell_DataType::TYPE_STRING);
                $currentSheet->setCellValueExplicit('I'.$cellIndex,'', \PHPExcel_Cell_DataType::TYPE_STRING);
                $currentSheet->setCellValueExplicit('J'.$cellIndex,"<img src=\"/uploadfile/product/".$value['sap_code']."/".$value['sap_code']."_04.jpg\" alt=\"\" /><img src=\"/uploadfile/product/".$value['sap_code']."/".$value['sap_code']."_05.jpg\" alt=\"\" />", \PHPExcel_Cell_DataType::TYPE_STRING);

                $currentSheet->setCellValueExplicit('K'.$cellIndex,$value['sap_code'],\PHPExcel_Cell_DataType::TYPE_STRING);
                $currentSheet->setCellValueExplicit('L'.$cellIndex,"https://www.gt-mall.cn/uploadfile/product/".$value['sap_code']."/".$value['sap_code']."_01.jpg", \PHPExcel_Cell_DataType::TYPE_STRING);
                $currentSheet->setCellValueExplicit('M'.$cellIndex,"https://www.gt-mall.cn/uploadfile/product/".$value['sap_code']."/".$value['sap_code']."_02.jpg", \PHPExcel_Cell_DataType::TYPE_STRING);
                $currentSheet->setCellValueExplicit('N'.$cellIndex,"https://www.gt-mall.cn/uploadfile/product/".$value['sap_code']."/".$value['sap_code']."_03.jpg", \PHPExcel_Cell_DataType::TYPE_STRING);
                $currentSheet->setCellValueExplicit('O'.$cellIndex,'', \PHPExcel_Cell_DataType::TYPE_STRING);

            }

            $name = uniqid().'.xls';
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="' . $name );
            header('Cache-Control: max-age=0');
            $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
            $objWriter->save('php://output');
            exit;

        }

    }

    /**
     * 2017-09-01
     * 大客户 VIP
     */
    function vipsupplieradd(){
        $this->display();
    }

    /**
     * 2017-09-01
     * 大客户 VIP
     */
    function getvipsuppliercategorycode(){

        $vipCategoryModel = M('vipCategory');
        $field = "U_nodecode,U_fathercode,U_nodename,U_is3C";
        $res = $vipCategoryModel->field($field)->select();
        //var_dump($res);die();
        $tree = array();
        foreach ($res as $key => $value)
        {
            // $key : 0, 1, 2, 3,
            // $value : array with key
            if ($value['U_fathercode']){
                $tree[] = array ('id'=>$value['U_nodecode'],'text'=>$value['U_nodename'],'pid'=>$value['U_fathercode'],'is3C'=>$value['U_is3C']);
            }else{
                $tree[] = array ('id'=>$value['U_nodecode'],'text'=>$value['U_nodename'],'checked'=>'true','is3C'=>$value['U_is3C']);
            }
        }
        echo json_encode($tree);
        exit;

    }

    /**
     * 2017-09-08
     * 导入权限表 FOR 数据权限
     */
    public function importpermissiontable()
    {
        $this->display();
    }

    /**
     * 2017-09-08
     * 执行导入权限表 FOR 数据权限
     */
    public function doImportPermissionTable()
    {
        //$time =time();
        $today = date("Y-m-d H:i:s");
        $time = $today;
        // excel 表头 与 mysql 表头对应关系
        $orderHeadArray = array(

            '物料简名' =>'item_short_name', //A
            '颜色' =>'color', //B
            '型号'=>'model', //C
            '规格'=>'specifications', //D
            '品牌(SAP系统内已有品牌）'=>'brand_name', //E - 需要找出 brand_id
            '品类(SAP系统内已有品类）'=>'category_code', //F - 需要转换为 code
            '重量'=>'weight', //G
            '订货周期'=>'ordering_day', //H
            '是否序列号管理'=>'is_serial', //I
            '产品经理'=>'pm', //J
            '采购价格'=>'OriginalPurchasePrice',//K
            'sap物料编号(非必填)' => 'sap_code', //L
            '备注'=>'remarkes', //M

        );


        if (!empty($_FILES)) {
            import("@.ORG.UploadFile");
            $config = array(
                'allowExts' => array('xlsx', 'xls'),
                'savePath' => './exceltojh/',
                'saveRule' => 'time',
            );
            $upload = new UploadFile($config);
            if (!$upload->upload($config['savePath'])) {
                $this->error($upload->getErrorMsg());
            } else {

                $info = $upload->getUploadFileInfo();
                $theType = $info[0]['type'];
                if($theType != "application/vnd.ms-excel")
                {
                    $this->assign('errorInfo',"文件类型错误！");
                    $this->display();
                    return;
                }

                $name = $info[0]['savename'];
                Vendor('Excel.PHPExcel');
                $filename= $config['savePath'].$name;

                $objPHPExcel = \PHPExcel_IOFactory::load($filename);

                $sheetData   = $objPHPExcel -> getActiveSheet() -> toArray(null, true, true, true);

                $currentSheet = $objPHPExcel->getSheet(0);
                $allColumn = $currentSheet->getHighestColumn();//取到最大列数
                $allRow = $currentSheet->getHighestRow();//取到最大行数

                // excel 中表头
                $excelHeadCN = $sheetData[1];
                $excelHead = array();
                foreach ($excelHeadCN as $key => $value) {
                    $excelHead[$key] = $orderHeadArray[$value];
                }
                unset($excelHead['']);
                foreach ($excelHead as $key => $value) {
                    if (empty($value)) {
                        unset($excelHead[$key]);
                    }
                }
                // Table表头与Excel列对应关系
                //var_dump($excelHead);
                unset($sheetData[1]); //删除excel表头 列名等行数据

                $mergeStr = '';
                $countNum = 0;
                foreach ($sheetData as $key => $v) {
                    //数据 $key行号 $v数组

                    $targetData = array();
                    foreach ($v as $inkey => $value) {
                        //Core
                        $targetData[$excelHead[$inkey]] = trim($value);
                    }
                    unset($targetData['']);

                    // 补全数据
                    $targetData['ctime'] = $time;
                    $targetData['utime'] = $time;

                    $emp_no = session('emp_no');
                    $targetData['emp_no'] = $emp_no;

                    $str = "'" . implode("','", $targetData) . "'";

                    $countNum++;

                    if ($countNum == 1) $mergeStr .= "({$str})";
                    else $mergeStr .= ", ({$str})";

                }
                $sql = " insert into think_sap_items  (" . implode(',', array_keys($targetData)) . ") values $mergeStr";
                //echo $sql;die();

                $sapbankRelationModel = M('M');
                $result = $sapbankRelationModel->execute($sql);
                $return = 0;
                $errorStr = '导入不成功！';
                if ($result) {
                    $return = 1;
                    $errorStr = '导入成功！';
                }
                //echo json_encode(array('data' => $return, 'msg' => $errorStr), 1);

                $this->assign('errorInfo',$errorStr);
                $this->display();

            }
        }
    }

    /**
     * 2017-09-13
     * 报表权限准备 - 入口页面
     */
    public function permissionentry()
    {
        $this->display();
    }

    /**
     * 2017-09-13
     * 毛利报表 - 页面
     */
    public function permissionmaoli(){

        // 员工ID
        //$auth_id = session('auth_id');
        //$emp_no = session('emp_no');

        // 员工部门 <= OA
        //$userRole = new UserRole();
        //$userInfo = $userRole->getUserRole($auth_id,$emp_no);
        //var_dump($userInfo);

        //$this->assign("emp_no",$emp_no);
        //$this->assign("userInfo",$userInfo);

        $this->assign("timeTagStart",$_REQUEST['timeTagStart']);
        $this->assign("timeTagComplete",$_REQUEST['timeTagComplete']);

        $this->display();
    }

    /**
     * 2017-09-13
     * 毛利报表 - 数据
     */
    public function permissionmaolidata(){

        // 员工ID
        $auth_id = session('auth_id');
        $emp_no = session('emp_no');

        // 员工部门 <= OA
        import("@.ORG.Util.UserRole");
        $userRole = new UserRole();
        $userInfo = $userRole->getUserRole($auth_id,$emp_no);
        $dept = $userInfo['dept'];
        $role = $userInfo['role'];
        $customerCode = $userInfo['Customer_Code'];

        import("@.ORG.Util.PermissionDatabase");
        $permissionDatabase = PermissionDatabase::getInstance();
        $model = $permissionDatabase->getModel();

        // 分页
        $sortOrder = I('sortOrder');
        //$sortField = I('sortField')?I('sortField').' '.$sortOrder:" OpSyDealDateTime desc, OpSyStatus desc ";
        $sortField = 'id';
        $pageIndex = I('pageIndex');
        $pageSize = I('pageSize')?:50;
        $where=" 1 = 1 ";
        $timeTagStart = $_REQUEST['timeTagStart'];
        $timeTagComplete = $_REQUEST['timeTagComplete'];
        $where .= " AND DocDate >= '{$timeTagStart}' AND DocDate <= '{$timeTagComplete}' ";
        switch ($dept)
        {
            case 'c4ca4238a0b923820dcc509a6f75849b':
                // 产品部 直线主管 查看数据 方法并入UserRole:
                $productManagerStaff = $userRole->getProductManagerStaff($emp_no);
                if(is_array($productManagerStaff)) {
                    $where .= " AND ";
                    foreach ($productManagerStaff as $staffKey => $staffValue) {
                        $count = $staffKey + 1;
                        if ($count == count($productManagerStaff)) {
                            $where .= " Pmanager = '{$staffValue['emp_no']}' ";
                        }else{
                            $where .= " Pmanager = '{$staffValue['emp_no']}' OR ";
                        }
                    }
                }else {
                    $where .= " AND Pmanager = '{$emp_no}' ";
                }
                break;
            case 'c81e728d9d4c2f636f067f89cc14862c':
                if(!empty($customerCode))
                {
                    $where .= " AND CardCode in ({$customerCode})";
                }
                break;
            default:
                break;
        }
        //echo $where;die();
        $total =$model->db(1)->table("profit_report")->where($where)->count();
        $res = $model->db(1)->table("profit_report")->where($where)->limit($pageIndex*$pageSize,$pageSize)->select();
        echo json_encode(array('total'=>$total,'data'=>$res));exit;

    }

    /**
     * 2017-09-25
     * 毛利报表 - Excel
     */
    public function permissionmaoliexcel(){

        // 员工ID
        $auth_id = session('auth_id');
        $emp_no = session('emp_no');

        // 员工部门 <= OA
        import("@.ORG.Util.UserRole");
        $userRole = new UserRole();
        $userInfo = $userRole->getUserRole($auth_id,$emp_no);
        $dept = $userInfo['dept'];
        $role = $userInfo['role'];
        $customerCode = $userInfo['Customer_Code'];

        import("@.ORG.Util.PermissionDatabase");
        $permissionDatabase = PermissionDatabase::getInstance();
        $model = $permissionDatabase->getModel();

        $where=" 1 = 1 ";
        $timeTagStart = $_REQUEST['timeTagStart'];
        $timeTagComplete = $_REQUEST['timeTagComplete'];
        $where .= " AND DocDate >= '{$timeTagStart}' AND DocDate <= '{$timeTagComplete}' ";
        switch ($dept)
        {
            case 'c4ca4238a0b923820dcc509a6f75849b':
                // 产品部 直线主管 查看数据 方法并入UserRole:
                $productManagerStaff = $userRole->getProductManagerStaff($emp_no);
                if(is_array($productManagerStaff)) {
                    $where .= " AND ";
                    foreach ($productManagerStaff as $staffKey => $staffValue) {
                        $count = $staffKey + 1;
                        if ($count == count($productManagerStaff)) {
                            $where .= " Pmanager = '{$staffValue['emp_no']}' ";
                        }else{
                            $where .= " Pmanager = '{$staffValue['emp_no']}' OR ";
                        }
                    }
                }else {
                    $where .= " AND Pmanager = '{$emp_no}' ";
                }
                break;
            case 'c81e728d9d4c2f636f067f89cc14862c':
                if(!empty($customerCode))
                {
                    $where .= " AND CardCode in ({$customerCode})";
                }
                break;
            default:
                break;
        }
        //echo $where;die();
        $data = $model->db(1)->table("profit_report")->where($where)->select();

        //Export to Excel:
        Vendor('Excel.PHPExcel');
        $objPHPExcel = new \PHPExcel();
        $currentSheet = $objPHPExcel->getSheet(0);
        $m = 1;
        $currentSheet->setCellValue('A'.$m, '订单号');
        $currentSheet->setCellValue('B'.$m, '平台编号');
        $currentSheet->setCellValue('C'.$m, '单据日期');
        $currentSheet->setCellValue('D'.$m, '物料号');
        $currentSheet->setCellValue('E'.$m, '物料名');

        $currentSheet->setCellValue('F'.$m, '数量');
        $currentSheet->setCellValue('G'.$m, '单价');
        $currentSheet->setCellValue('H'.$m, '小计');
        $currentSheet->setCellValue('I'.$m, '成本');
        $currentSheet->setCellValue('J'.$m, '成本小计');

        $currentSheet->setCellValue('K'.$m, '银行费用');
        $currentSheet->setCellValue('L'.$m, '预估运费');
        $currentSheet->setCellValue('M'.$m, '结算运费');
        $currentSheet->setCellValue('N'.$m, '赠品数');
        $currentSheet->setCellValue('O'.$m, '赠品价值');

        $currentSheet->setCellValue('P'.$m, '赠品种类');
        $currentSheet->setCellValue('Q'.$m, '赠品运费');
        $currentSheet->setCellValue('R'.$m, '产品经理');
        $currentSheet->setCellValue('S'.$m, '代发');
        $currentSheet->setCellValue('T'.$m, '计数运费');

        $currentSheet->setCellValue('U'.$m, '物流附加');
        $currentSheet->setCellValue('V'.$m, '计算成本');
        $currentSheet->setCellValue('W'.$m, '计算税');
        $currentSheet->setCellValue('X'.$m, '产品组长');
        $currentSheet->setCellValue('Y'.$m, '是否预估手续费');

        $cellIndex = 1;
        foreach ($data as $key => $value){
            $cellIndex++;
            $currentSheet->setCellValueExplicit('A'.$cellIndex,$value['FreeTxt'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('B'.$cellIndex,$value['CardCode'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('C'.$cellIndex,$value['DocDate'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('D'.$cellIndex,$value['ITEMCODE'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('E'.$cellIndex,$value['ITEMNAME'],\PHPExcel_Cell_DataType::TYPE_STRING);

            $currentSheet->setCellValueExplicit('F'.$cellIndex,$value['Quantity'],\PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('G'.$cellIndex,$value['Price'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('H'.$cellIndex,$value['linetotal'],\PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('I'.$cellIndex,$value['StockPrice'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('J'.$cellIndex,$value['LineStockPrice'], \PHPExcel_Cell_DataType::TYPE_STRING);

            $currentSheet->setCellValueExplicit('K'.$cellIndex,$value['bankcharge'],\PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('L'.$cellIndex,$value['EstimateExpCost'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('M'.$cellIndex,$value['TureExpCost'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('N'.$cellIndex,$value['giftcount'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('O'.$cellIndex,$value['giftprice'], \PHPExcel_Cell_DataType::TYPE_STRING);

            $currentSheet->setCellValueExplicit('P'.$cellIndex,$value['giftkind'],\PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('Q'.$cellIndex,$value['giftaddexpressfee'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('R'.$cellIndex,$value['Pmanager'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('S'.$cellIndex,$value['isBehalf'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('T'.$cellIndex,$value['calcexpressfee'], \PHPExcel_Cell_DataType::TYPE_STRING);

            $currentSheet->setCellValueExplicit('U'.$cellIndex,$value['addexpressfee'],\PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('V'.$cellIndex,$value['calclineStockprice'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('W'.$cellIndex,$value['calctax'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('X'.$cellIndex,$value['Pleader'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('Y'.$cellIndex,$value['IsEstimateBankFee'], \PHPExcel_Cell_DataType::TYPE_STRING);

        }

        $name = uniqid().'.xls';
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $name );
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;

    }

    /**
     * 2017-09-14
     * 销售报表 - 页面
     */
    public function permissionxiaoshou(){

        // 员工ID
        $auth_id = session('auth_id');
        $emp_no = session('emp_no');

        // 员工部门 <= OA
        import("@.ORG.Util.UserRole");
        $userRole = new UserRole();
        $userInfo = $userRole->getUserRole($auth_id,$emp_no);
        //var_dump($userInfo);

        $this->assign("emp_no",$emp_no);
        $this->assign("userInfo",$userInfo);

        $this->assign("timeTagStart",$_REQUEST['timeTagStart']);
        $this->assign("timeTagComplete",$_REQUEST['timeTagComplete']);

        $this->display();
    }

    /**
     * 2017-09-14
     * 销售报表 - 数据
     */
    public function permissionxiaoshoudata(){

        // 员工ID
        $auth_id = session('auth_id');
        $emp_no = session('emp_no');

        // 员工部门 <= OA
        import("@.ORG.Util.UserRole");
        $userRole = new UserRole();
        $userInfo = $userRole->getUserRole($auth_id,$emp_no);
        $dept = $userInfo['dept'];
        $role = $userInfo['role'];
        $customerCode = $userInfo['Customer_Code'];

        import("@.ORG.Util.PermissionDatabase");
        $permissionDatabase = PermissionDatabase::getInstance();
        $model = $permissionDatabase->getModel();

        // 分页
        $sortOrder = I('sortOrder');
        //$sortField = I('sortField')?I('sortField').' '.$sortOrder:" OpSyDealDateTime desc, OpSyStatus desc ";
        $sortField = 'id';
        $pageIndex = I('pageIndex');
        $pageSize = I('pageSize')?:50;
        $where=" 1 = 1 ";
        $field = '*';
        $timeTagStart = $_REQUEST['timeTagStart'];
        $timeTagComplete = $_REQUEST['timeTagComplete'];
        $where .= " AND DocDate >= '{$timeTagStart}' AND DocDate <= '{$timeTagComplete}' ";
        switch ($dept)
        {
            case 'c4ca4238a0b923820dcc509a6f75849b':
                // 产品部 直线主管 查看数据 方法并入UserRole:
                $productManagerStaff = $userRole->getProductManagerStaff($emp_no);
                if(is_array($productManagerStaff)) {
                    $where .= " AND ";
                    foreach ($productManagerStaff as $staffKey => $staffValue) {
                        $count = $staffKey + 1;
                        if ($count == count($productManagerStaff)) {
                            $where .= " Pmanager = '{$staffValue['emp_no']}' ";
                        }else{
                            $where .= " Pmanager = '{$staffValue['emp_no']}' OR ";
                        }
                    }
                }else {
                    $where .= " AND Pmanager = '{$emp_no}' ";
                }
                $field = " `ItemCode`, `ItemName`, `Color`, `Model`, `OrderId`, `Qty`, `DocDate`, `DocTime`, `OStatus`, `Total`, `WhsCode`, `WhsName`, `Phone`, `Cstname`, `Repname`, `zipcode`, `InType`, `ExpCom`, `ExpNo`, `ExpCost`, `InHead`, `Conrec`, `Address`, `State`, `City`, `County`, `OTPhone`, `SerNum`, `Weight`, `Replac`, `PManager`, `Is3C`, `PurPrice`";
                break;
            case 'c81e728d9d4c2f636f067f89cc14862c':
                if(!empty($customerCode))
                {
                    $where .= " AND CardCode in ({$customerCode})";
                }
                $field = " `CardCode`, `CardName`, `ItemCode`, `ItemName`, `Color`, `Model`, `CitemCd`, `CitemNm`, `OrderId`, `Qty`, `DocDate`, `DocTime`, `OStatus`, `Price`, `Total`, `WhsCode`, `WhsName`, `Phone`, `Cstname`, `Repname`, `zipcode`, `NoDPrc`, `InType`, `ExpCom`, `ExpNo`, `ExpCost`, `InHead`, `Conrec`, `Address`, `State`, `City`, `County`, `GoodsFee`, `OTPhone`, `SerNum`, `Weight`, `Replac`, `PManager`, `Is3C`, `charge`";
                break;
            default:
                break;
        }
        //echo $where;die();
        $total =$model->db(1)->table("sales_order")->field($field)->where($where)->count();
        $res = $model->db(1)->table("sales_order")->field($field)->where($where)->limit($pageIndex*$pageSize,$pageSize)->select();
        echo json_encode(array('total'=>$total,'data'=>$res));exit;

    }

    /**
     * 2017-09-25
     * 销售报表 - Excel
     */
    public function permissionxiaoshouexcel(){

        // 员工ID
        $auth_id = session('auth_id');
        $emp_no = session('emp_no');

        // 员工部门 <= OA
        import("@.ORG.Util.UserRole");
        $userRole = new UserRole();
        $userInfo = $userRole->getUserRole($auth_id,$emp_no);
        $dept = $userInfo['dept'];
        $role = $userInfo['role'];
        $customerCode = $userInfo['Customer_Code'];

        import("@.ORG.Util.PermissionDatabase");
        $permissionDatabase = PermissionDatabase::getInstance();
        $model = $permissionDatabase->getModel();

        $where=" 1 = 1 ";
        $field = '*';
        $timeTagStart = $_REQUEST['timeTagStart'];
        $timeTagComplete = $_REQUEST['timeTagComplete'];
        $where .= " AND DocDate >= '{$timeTagStart}' AND DocDate <= '{$timeTagComplete}' ";
        switch ($dept)
        {
            case 'c4ca4238a0b923820dcc509a6f75849b':
                // 产品部 直线主管 查看数据 方法并入UserRole:
                $productManagerStaff = $userRole->getProductManagerStaff($emp_no);
                if(is_array($productManagerStaff)) {
                    $where .= " AND ";
                    foreach ($productManagerStaff as $staffKey => $staffValue) {
                        $count = $staffKey + 1;
                        if ($count == count($productManagerStaff)) {
                            $where .= " Pmanager = '{$staffValue['emp_no']}' ";
                        }else{
                            $where .= " Pmanager = '{$staffValue['emp_no']}' OR ";
                        }
                    }
                }else {
                    $where .= " AND Pmanager = '{$emp_no}' ";
                }
                $field = " `ItemCode`, `ItemName`, `Color`, `Model`, `OrderId`, `Qty`, `DocDate`, `DocTime`, `OStatus`, `Total`, `WhsCode`, `WhsName`, `Phone`, `Cstname`, `Repname`, `zipcode`, `InType`, `ExpCom`, `ExpNo`, `ExpCost`, `InHead`, `Conrec`, `Address`, `State`, `City`, `County`, `OTPhone`, `SerNum`, `Weight`, `Replac`, `PManager`, `Is3C`, `PurPrice`";
                break;
            case 'c81e728d9d4c2f636f067f89cc14862c':
                if(!empty($customerCode))
                {
                    $where .= " AND CardCode in ({$customerCode})";
                }
                $field = " `CardCode`, `CardName`, `ItemCode`, `ItemName`, `Color`, `Model`, `CitemCd`, `CitemNm`, `OrderId`, `Qty`, `DocDate`, `DocTime`, `OStatus`, `Price`, `Total`, `WhsCode`, `WhsName`, `Phone`, `Cstname`, `Repname`, `zipcode`, `NoDPrc`, `InType`, `ExpCom`, `ExpNo`, `ExpCost`, `InHead`, `Conrec`, `Address`, `State`, `City`, `County`, `GoodsFee`, `OTPhone`, `SerNum`, `Weight`, `Replac`, `PManager`, `Is3C`, `charge`";
                break;
            default:
                break;
        }
        //echo $where;die();
        //$total =$model->db(1)->table("sales_order")->field($field)->where($where)->count();
        //var_dump($total);die();
        $data = $model->db(1)->table("sales_order")->field($field)->where($where)->select();

        //Export to Excel:
        Vendor('Excel.PHPExcel');
        $objPHPExcel = new \PHPExcel();
        $currentSheet = $objPHPExcel->getSheet(0);
        $m = 1;
        $currentSheet->setCellValue('A'.$m, '平台代码');
        $currentSheet->setCellValue('B'.$m, '平台名称');
        $currentSheet->setCellValue('C'.$m, '物料代码');
        $currentSheet->setCellValue('D'.$m, '物料描述');
        $currentSheet->setCellValue('E'.$m, '颜色');

        $currentSheet->setCellValue('F'.$m, '型号');
        $currentSheet->setCellValue('G'.$m, '客户物料号');
        $currentSheet->setCellValue('H'.$m, '客户物料名称');
        $currentSheet->setCellValue('I'.$m, '订单号');
        $currentSheet->setCellValue('J'.$m, '数量');

        $currentSheet->setCellValue('K'.$m, '单据日期');
        $currentSheet->setCellValue('L'.$m, '订单时间');
        $currentSheet->setCellValue('M'.$m, '订单状态');
        $currentSheet->setCellValue('N'.$m, '价格');
        $currentSheet->setCellValue('O'.$m, '总计');

        $currentSheet->setCellValue('P'.$m, '仓库代码');
        $currentSheet->setCellValue('Q'.$m, '仓库名称');
        $currentSheet->setCellValue('R'.$m, '结算价格');
        $currentSheet->setCellValue('S'.$m, '发票类型');
        $currentSheet->setCellValue('T'.$m, '快递公司');

        $currentSheet->setCellValue('U'.$m, '快递单号');
        $currentSheet->setCellValue('V'.$m, '快递费');
        $currentSheet->setCellValue('W'.$m, '是否确认收货');
        $currentSheet->setCellValue('X'.$m, '省');
        $currentSheet->setCellValue('Y'.$m, '市');

        $currentSheet->setCellValue('Z'.$m, '县');
        $currentSheet->setCellValue('AA'.$m, '实际支付金额');
        $currentSheet->setCellValue('AB'.$m, '序列号');
        $currentSheet->setCellValue('AC'.$m, '核重');
        $currentSheet->setCellValue('AD'.$m, '是否代发');

        $currentSheet->setCellValue('AE'.$m, '产品经理');
        $currentSheet->setCellValue('AF'.$m, '3C非3C产品');
        $currentSheet->setCellValue('AG'.$m, '物料采购价格');
        $currentSheet->setCellValue('AH'.$m, '手续费暂估');

        $cellIndex = 1;
        foreach ($data as $key => $value){
            $cellIndex++;
            $currentSheet->setCellValueExplicit('A'.$cellIndex,$value['CardCode'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('B'.$cellIndex,$value['CardName'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('C'.$cellIndex,$value['ItemCode'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('D'.$cellIndex,$value['ItemName'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('E'.$cellIndex,$value['Color'],\PHPExcel_Cell_DataType::TYPE_STRING);

            $currentSheet->setCellValueExplicit('F'.$cellIndex,$value['Model'],\PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('G'.$cellIndex,$value['CitemCd'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('H'.$cellIndex,$value['CitemNm'],\PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('I'.$cellIndex,$value['OrderId'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('J'.$cellIndex,$value['Qty'], \PHPExcel_Cell_DataType::TYPE_STRING);

            $currentSheet->setCellValueExplicit('K'.$cellIndex,$value['DocDate'],\PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('L'.$cellIndex,$value['DocTime'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('M'.$cellIndex,$value['OStatus'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('N'.$cellIndex,$value['Price'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('O'.$cellIndex,$value['Total'], \PHPExcel_Cell_DataType::TYPE_STRING);

            $currentSheet->setCellValueExplicit('P'.$cellIndex,$value['WhsCode'],\PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('Q'.$cellIndex,$value['WhsName'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('R'.$cellIndex,$value['NoDPrc'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('S'.$cellIndex,$value['InType'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('T'.$cellIndex,$value['ExpCom'], \PHPExcel_Cell_DataType::TYPE_STRING);

            $currentSheet->setCellValueExplicit('U'.$cellIndex,$value['ExpNo'],\PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('V'.$cellIndex,$value['ExpCost'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('W'.$cellIndex,$value['Conrec'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('X'.$cellIndex,$value['State'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('Y'.$cellIndex,$value['City'], \PHPExcel_Cell_DataType::TYPE_STRING);

            $currentSheet->setCellValueExplicit('Z'.$cellIndex,$value['County'],\PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AA'.$cellIndex,$value['GoodsFee'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AB'.$cellIndex,$value['SerNum'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AC'.$cellIndex,$value['Weight'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AD'.$cellIndex,$value['Replac'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AE'.$cellIndex,$value['PManager'], \PHPExcel_Cell_DataType::TYPE_STRING);

            $currentSheet->setCellValueExplicit('AF'.$cellIndex,$value['Is3C'],\PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AG'.$cellIndex,$value['PurPrice'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AH'.$cellIndex,$value['charge'], \PHPExcel_Cell_DataType::TYPE_STRING);

        }

        $name = uniqid().'.xls';
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $name );
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;

    }

    /**
     * 2017-09-14
     * 采购报表 - 页面
     */
    public function permissioncaigou(){

        // 员工ID
        $auth_id = session('auth_id');
        $emp_no = session('emp_no');

        // 员工部门 <= OA
        import("@.ORG.Util.UserRole");
        $userRole = new UserRole();
        $userInfo = $userRole->getUserRole($auth_id,$emp_no);
        //var_dump($userInfo);

        $this->assign("emp_no",$emp_no);
        $this->assign("userInfo",$userInfo);

        $this->assign("timeTagStart",$_REQUEST['timeTagStart']);
        $this->assign("timeTagComplete",$_REQUEST['timeTagComplete']);

        $this->display();
    }

    /**
     * 2017-09-14
     * 采购报表 - 数据
     */
    public function permissioncaigoudata(){

        // 员工ID
        $auth_id = session('auth_id');
        $emp_no = session('emp_no');

        // 员工部门 <= OA
        import("@.ORG.Util.UserRole");
        $userRole = new UserRole();
        $userInfo = $userRole->getUserRole($auth_id,$emp_no);
        $dept = $userInfo['dept'];
        $role = $userInfo['role'];
        $customerCode = $userInfo['Customer_Code'];

        import("@.ORG.Util.PermissionDatabase");
        $permissionDatabase = PermissionDatabase::getInstance();
        $model = $permissionDatabase->getModel();

        // 分页
        $sortOrder = I('sortOrder');
        //$sortField = I('sortField')?I('sortField').' '.$sortOrder:" OpSyDealDateTime desc, OpSyStatus desc ";
        $sortField = 'id';
        $pageIndex = I('pageIndex');
        $pageSize = I('pageSize')?:50;
        $where=" 1 = 1 ";
        $field = '*';
        $timeTagStart = $_REQUEST['timeTagStart'];
        $timeTagComplete = $_REQUEST['timeTagComplete'];
        $where .= " AND docdate >= '{$timeTagStart}' AND docdate <= '{$timeTagComplete}' ";
        switch ($dept)
        {
            case 'c4ca4238a0b923820dcc509a6f75849b':
                // 产品部 直线主管 查看数据 方法并入UserRole:
                $productManagerStaff = $userRole->getProductManagerStaff($emp_no);
                if(is_array($productManagerStaff)) {
                    $where .= " AND ";
                    foreach ($productManagerStaff as $staffKey => $staffValue) {
                        $count = $staffKey + 1;
                        if ($count == count($productManagerStaff)) {
                            $where .= " u_pmanager = '{$staffValue['emp_no']}' ";
                        }else{
                            $where .= " u_pmanager = '{$staffValue['emp_no']}' OR ";
                        }
                    }
                }else {
                    $where .= " AND u_pmanager = '{$emp_no}' ";
                }
                $field = "  `phone1`, `address`, `name1`, `tel1`, `E_mail1`, `name2`, `tel2`, `E_mail2`, `introducer`, `contactstart`, `contactend`, `dflaccount`, `bankcode`, `Docnum`, `docdate`, `docdudate`, `Itemcode`, `Dscription`, `U_SO002`, `U_CG003`, `u_is3c`, `u_pmanager`, `slpname`, `Quantity`, `U_CG002`, `PriceBefDi`, `LineTotal`, `DocTotal`";
                //`SupplierCode`, `SupplierName`,
                break;
            case 'c81e728d9d4c2f636f067f89cc14862c':
                if(!empty($customerCode))
                {
                    $where .= " AND CardCode in ({$customerCode})";
                }
                $field = "  `CardCode`, `CardName`, `phone1`, `address`, `name1`, `tel1`, `E_mail1`, `name2`, `tel2`, `E_mail2`, `introducer`, `contactstart`, `contactend`, `dflaccount`, `bankcode`, `Docnum`, `docdate`, `docdudate`, `Itemcode`, `Dscription`, `U_SO002`, `U_CG003`, `u_is3c`, `u_pmanager`, `slpname`";
                //`SupplierCode`, `SupplierName`,
                break;
            default:
                break;
        }
        //echo $where;die();
        $total =$model->db(1)->table("purchase_order")->field($field)->where($where)->count();
        $res = $model->db(1)->table("purchase_order")->field($field)->where($where)->limit($pageIndex*$pageSize,$pageSize)->select();
        echo json_encode(array('total'=>$total,'data'=>$res));exit;

    }

    /**
     * 2017-09-25
     * 采购报表 - Excel
     */
    public function permissioncaigouexcel(){

        // 员工ID
        $auth_id = session('auth_id');
        $emp_no = session('emp_no');

        // 员工部门 <= OA
        import("@.ORG.Util.UserRole");
        $userRole = new UserRole();
        $userInfo = $userRole->getUserRole($auth_id,$emp_no);
        $dept = $userInfo['dept'];
        $role = $userInfo['role'];
        $customerCode = $userInfo['Customer_Code'];

        import("@.ORG.Util.PermissionDatabase");
        $permissionDatabase = PermissionDatabase::getInstance();
        $model = $permissionDatabase->getModel();

        $where=" 1 = 1 ";
        $field = '*';
        $timeTagStart = $_REQUEST['timeTagStart'];
        $timeTagComplete = $_REQUEST['timeTagComplete'];
        $where .= " AND DocDate >= '{$timeTagStart}' AND DocDate <= '{$timeTagComplete}' ";
        switch ($dept)
        {
            case 'c4ca4238a0b923820dcc509a6f75849b':
                // 产品部 直线主管 查看数据 方法并入UserRole:
                $productManagerStaff = $userRole->getProductManagerStaff($emp_no);
                if(is_array($productManagerStaff)) {
                    $where .= " AND ";
                    foreach ($productManagerStaff as $staffKey => $staffValue) {
                        $count = $staffKey + 1;
                        if ($count == count($productManagerStaff)) {
                            $where .= " u_pmanager = '{$staffValue['emp_no']}' ";
                        }else{
                            $where .= " u_pmanager = '{$staffValue['emp_no']}' OR ";
                        }
                    }
                }else {
                    $where .= " AND u_pmanager = '{$emp_no}' ";
                }
                $field = " `phone1`, `address`, `name1`, `tel1`, `E_mail1`, `name2`, `tel2`, `E_mail2`, `introducer`, `contactstart`, `contactend`, `dflaccount`, `bankcode`, `Docnum`, `docdate`, `docdudate`, `Itemcode`, `Dscription`, `U_SO002`, `U_CG003`, `u_is3c`, `u_pmanager`, `slpname`, `Quantity`, `U_CG002`, `PriceBefDi`, `LineTotal`, `DocTotal`";
                //`SupplierCode`, `SupplierName`,
                break;
            case 'c81e728d9d4c2f636f067f89cc14862c':
                if(!empty($customerCode))
                {
                    $where .= " AND CardCode in ({$customerCode})";
                }
                $field = " `CardCode`, `CardName`, `phone1`, `address`, `name1`, `tel1`, `E_mail1`, `name2`, `tel2`, `E_mail2`, `introducer`, `contactstart`, `contactend`, `dflaccount`, `bankcode`, `Docnum`, `docdate`, `docdudate`, `Itemcode`, `Dscription`, `U_SO002`, `U_CG003`, `u_is3c`, `u_pmanager`, `slpname`";
                //`SupplierCode`, `SupplierName`,
                break;
            default:
                break;
        }
        //echo $where;die();
        $data = $model->db(1)->table("purchase_order")->field($field)->where($where)->select();

        //Export to Excel:
        Vendor('Excel.PHPExcel');
        $objPHPExcel = new \PHPExcel();
        $currentSheet = $objPHPExcel->getSheet(0);
        $m = 1;
        $currentSheet->setCellValue('A'.$m, '平台代码');
        $currentSheet->setCellValue('B'.$m, '平台名称');
        $currentSheet->setCellValue('C'.$m, '供应商代码');
        $currentSheet->setCellValue('D'.$m, '供应商名称');
        $currentSheet->setCellValue('E'.$m, '供应商电话');

        $currentSheet->setCellValue('F'.$m, '供应商地址');
        $currentSheet->setCellValue('G'.$m, '业务主管');
        $currentSheet->setCellValue('H'.$m, '主管联系电话');
        $currentSheet->setCellValue('I'.$m, '主管邮箱');
        $currentSheet->setCellValue('J'.$m, '业务员');

        $currentSheet->setCellValue('K'.$m, '业务员电话');
        $currentSheet->setCellValue('L'.$m, '业务员邮箱');
        $currentSheet->setCellValue('M'.$m, '引入产品经理');
        $currentSheet->setCellValue('N'.$m, '合同起始时间');
        $currentSheet->setCellValue('O'.$m, '合同到期时间');

        $currentSheet->setCellValue('P'.$m, '银行卡号');
        $currentSheet->setCellValue('Q'.$m, '银行卡开户名称');
        $currentSheet->setCellValue('R'.$m, '采购订单号');
        $currentSheet->setCellValue('S'.$m, '单据时间');
        $currentSheet->setCellValue('T'.$m, '到货时间');

        $currentSheet->setCellValue('U'.$m, '物料编号');
        $currentSheet->setCellValue('V'.$m, '物料名称');
        $currentSheet->setCellValue('W'.$m, '型号');
        $currentSheet->setCellValue('X'.$m, '颜色');
        $currentSheet->setCellValue('Y'.$m, '是否3C');

        $currentSheet->setCellValue('Z'.$m, '产品经理');
        $currentSheet->setCellValue('AA'.$m, '采购员');
        $currentSheet->setCellValue('AB'.$m, '数量');
        $currentSheet->setCellValue('AC'.$m, '上次采购价格');
        $currentSheet->setCellValue('AD'.$m, '采购单价');

        $currentSheet->setCellValue('AE'.$m, '采购小计');
        $currentSheet->setCellValue('AF'.$m, '采购总计');

        $cellIndex = 1;
        foreach ($data as $key => $value){
            $cellIndex++;
            $currentSheet->setCellValueExplicit('A'.$cellIndex,$value['CardCode'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('B'.$cellIndex,$value['CardName'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('C'.$cellIndex,$value['SupplierCode'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('D'.$cellIndex,$value['SupplierName'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('E'.$cellIndex,$value['phone1'],\PHPExcel_Cell_DataType::TYPE_STRING);

            $currentSheet->setCellValueExplicit('F'.$cellIndex,$value['address'],\PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('G'.$cellIndex,$value['name1'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('H'.$cellIndex,$value['tel1'],\PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('I'.$cellIndex,$value['E_mail1'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('J'.$cellIndex,$value['name2'], \PHPExcel_Cell_DataType::TYPE_STRING);

            $currentSheet->setCellValueExplicit('K'.$cellIndex,$value['tel2'],\PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('L'.$cellIndex,$value['E_mail2'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('M'.$cellIndex,$value['introducer'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('N'.$cellIndex,$value['contactstart'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('O'.$cellIndex,$value['contactend'], \PHPExcel_Cell_DataType::TYPE_STRING);

            $currentSheet->setCellValueExplicit('P'.$cellIndex,$value['dflaccount'],\PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('Q'.$cellIndex,$value['bankcode'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('R'.$cellIndex,$value['Docnum'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('S'.$cellIndex,$value['docdate'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('T'.$cellIndex,$value['docdudate'], \PHPExcel_Cell_DataType::TYPE_STRING);

            $currentSheet->setCellValueExplicit('U'.$cellIndex,$value['Itemcode'],\PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('V'.$cellIndex,$value['Dscription'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('W'.$cellIndex,$value['U_SO002'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('X'.$cellIndex,$value['U_CG003'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('Y'.$cellIndex,$value['u_is3c'], \PHPExcel_Cell_DataType::TYPE_STRING);

            $currentSheet->setCellValueExplicit('Z'.$cellIndex,$value['u_pmanager'],\PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AA'.$cellIndex,$value['slpname'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AB'.$cellIndex,$value['Quantity'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AC'.$cellIndex,$value['U_CG002'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AD'.$cellIndex,$value['PriceBefDi'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $currentSheet->setCellValueExplicit('AE'.$cellIndex,$value['LineTotal'], \PHPExcel_Cell_DataType::TYPE_STRING);

            $currentSheet->setCellValueExplicit('AF'.$cellIndex,$value['DocTotal'],\PHPExcel_Cell_DataType::TYPE_STRING);

        }

        $name = uniqid().'.xls';
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $name );
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;

    }

    public function warehouse3upload()
    {
        $this->display();
    }

    public function warehouse3execute(){
        $time =time();

        // excel表头 与 SAP的对应关系
        $orderHeadArray = array(

            '来源单号' =>'TMP_ID', //G
            '快递公司' =>'ExpCom', //H
            '快递单号'=>'ExpNo', //M

        );

        $html = "";
        $errorlist = array();
        $echoStr = '';
        $cellIndex = 5;
        ini_set("max_execution_time", "1800");
        import("@.ORG.Util.Sqlserver");
        $db = new Sqlserver();
        //Change to PDO_DBLIB
        //$db = new PDO_DBLIB_MSSQL();
        if (!empty($_FILES)) {
            import("@.ORG.UploadFile");
            $config=array(
                'allowExts'=>array('xlsx','xls'),
                'savePath'=>'./exceltojh/',
                'saveRule'=>'time',
            );
            $upload = new UploadFile($config);
            if (!$upload->upload($config['savePath'])) {
                $this->error($upload->getErrorMsg());
            } else {
                $is_sign = 0;
                $info = $upload->getUploadFileInfo();
                $name = $info[0]['savename'];
                Vendor('Excel.PHPExcel');
                $filename= $config['savePath'].$name;
                // echo $filename;exit;
                //导入thinkphp第三方类库
                $objPHPExcel = \PHPExcel_IOFactory::load($filename);

                $sheetData   = $objPHPExcel -> getActiveSheet() -> toArray(null, true, true, true);

                $currentSheet = $objPHPExcel->getSheet(0);
                //echo $currentSheet;exit;
                $allColumn = $currentSheet->getHighestColumn();//取到最大列数
                $allRow = $currentSheet->getHighestRow();//取到最大行数
                //echo $allRow;exit;

                // excel 中表头
                $excelHeadCN = $sheetData[2];
                $excelHead = array();
                foreach ($excelHeadCN as $key => $value){
                    //$excelHead[$orderHeadArray[$value]] = $key;
                    $excelHead[$key] = $orderHeadArray[$value];
                }
                unset($excelHead['']);
                foreach ($excelHead as $key => $value)
                {
                    if (empty($value)){
                        unset($excelHead[$key]);
                    }
                }
                // SAP表头与Excel列对应关系
                //var_dump($excelHead);

                unset($sheetData[1],$sheetData[2]); //删除excel表头 列名等行数据

                $mergeStr = '';
                $countNum = 0;

                foreach ($sheetData as $key => $v) {
                    //数据 $key行号 $v数组

                    $targetData = array();
                    foreach ($v as $key => $value)
                    {
                        $targetData[$excelHead[$key]] = trim($value);
                    }
                    unset($targetData['']);

                    // 补全数据
                    $orderArray = explode('~',$targetData['TMP_ID']);
                    //var_dump($orderArray);die();
                    if(is_array($orderArray)){
                        $targetData['DocEntry']=$orderArray[1];
                        $targetData['OrderId']=$orderArray[0];
                        $targetData['Lineid']=$orderArray[2];
                        unset($targetData['TMP_ID']);
                    }
                    $targetData['Phone'] = 'xxxxxxxxxxx';

                    if($targetData['DocEntry'])
                    $str = "'".implode("','", $targetData)."'";

                    $countNum++;

                    if ($countNum == 1) $mergeStr .= "({$str})";
                    else $mergeStr .= ", ({$str})";
                    //var_dump($mergeStr);

                }

                $sql =" insert into [dbo].[Import_Z0090]  (" .implode(',', array_keys($targetData) ) .") values $mergeStr";
                //echo $sql;
                //die();
                $sql= mb_convert_encoding($sql, "GBK", "UTF-8");
                $result = $db->saveBysql($sql);

                $db->close();

                if ($result)
                    $this->assign('importResult', 'YES');
                else
                    $this->assign('importResult', 'NO');

                $this->display('warehouse3result');

            }


        }





    }

    public function jiaohangorderupload()
    {
        $this->display();
    }
    public function jiaohangorderexecute(){
        $time =time();

        // excel表头 与 SAP的对应关系
        $orderHeadArray = array(

            '订单编号' =>'U_OrderId', //A
            '订购时间' =>'U_DocDate', //B
            '收货人姓名'=>'U_Cstname', //C
            '收货人联系方式'=>'U_Phone', //D
            '收货人地址'=>'U_Address', //E

            '邮编' =>'U_zipcode', //F
            '发票抬头' =>'U_InHead', //G
            '商品编号'=>'U_CitemCd', //H
            '商品名称'=>'U_CitemNm', //I

            '分期数' =>'U_FQQTY', //K
            '交行价' =>'U_Price', //L
            '购买数量'=>'U_Qty', //M
            '总金额'=>'U_Total', //N
            '佣金值'=>'U_DisCt', //O

            '支付金额' =>'U_GoodsFee', //P
            '配送规格'=>'U_DelTime', //R

            '订单备注'=>'U_Memo', //Z
            '颜色'=>'U_Color', //AB

        );

        $html = "";
        $errorlist = array();
        $echoStr = '';
        $cellIndex = 5;
        ini_set("max_execution_time", "1800");
        import("@.ORG.Util.Sqlserver");
        $db = new Sqlserver();
        //Change to PDO_DBLIB
        //$db = new PDO_DBLIB_MSSQL();
        if (!empty($_FILES)) {
            import("@.ORG.UploadFile");
            $config=array(
                'allowExts'=>array('xlsx','xls'),
                'savePath'=>'./exceltojh/',
                'saveRule'=>'time',
            );
            $upload = new UploadFile($config);
            if (!$upload->upload($config['savePath'])) {
                $this->error($upload->getErrorMsg());
            } else {
                $is_sign = 0;
                $info = $upload->getUploadFileInfo();
                $name = $info[0]['savename'];
                Vendor('Excel.PHPExcel');
                $filename= $config['savePath'].$name;
                // echo $filename;exit;
                //导入thinkphp第三方类库
                $objPHPExcel = \PHPExcel_IOFactory::load($filename);

                $sheetData   = $objPHPExcel -> getActiveSheet() -> toArray(null, true, true, true);

                $currentSheet = $objPHPExcel->getSheet(0);
                //echo $currentSheet;exit;
                $allColumn = $currentSheet->getHighestColumn();//取到最大列数
                $allRow = $currentSheet->getHighestRow();//取到最大行数
                //echo $allRow;exit;

                // excel 中表头
                $excelHeadCN = $sheetData[1];
                $excelHead = array();
                foreach ($excelHeadCN as $key => $value){
                    //$excelHead[$orderHeadArray[$value]] = $key;
                    $excelHead[$key] = $orderHeadArray[$value];
                }
                unset($excelHead['']);
                foreach ($excelHead as $key => $value)
                {
                    if (empty($value)){
                        unset($excelHead[$key]);
                    }
                }
                // SAP表头与Excel列对应关系
                //var_dump($excelHead);

                unset($sheetData[1]); //删除excel表头 列名等行数据

                $mergeStr = '';
                $countNum = 0;

                foreach ($sheetData as $key => $v) {
                    //数据 $key行号 $v数组

                    $targetData = array();
                    foreach ($v as $key => $value)
                    {
                        $targetData[$excelHead[$key]] = trim($value);
                    }
                    unset($targetData['']);

                    // 补全数据
                    $tmpPhoneA = explode('，',$targetData['U_Phone']);
                    if(is_array($tmpPhoneA)){
                        $tmpPhoneB = explode('：',$tmpPhoneA[0]);
                        if(is_array($tmpPhoneB))
                        {
                            $targetData['U_Phone'] = $tmpPhoneB[1];
                        }
                    }
                    //echo $targetData['U_Phone'];die();
                    $tmpAddress = explode('，',$targetData['U_Address']);
                    if(is_array($tmpAddress)){
                        //var_dump($tmpAddress);die();
                        $targetData['U_State'] = $tmpAddress[0];
                        //echo "<br>";
                        $targetData['U_City'] = $tmpAddress[1];
                        //echo "<br>";
                        $targetData['U_Address'] = $tmpAddress[count($tmpAddress)-1];
                    }

                    $targetData['U_charge'] = $targetData['U_DisCt'];
                    $targetData['U_DelTimeQ'] = $targetData['U_DelTime'];
                    $targetData['U_CardCode'] = "C20057";
                    $targetData['U_Bat'] = $time;
                    $targetData['U_InptCode'] = "T048";

                    //convert to string
                        $str = "'".implode("','", $targetData)."'";

                    $countNum++;

                    if ($countNum == 1) $mergeStr .= "({$str})";
                    else $mergeStr .= ", ({$str})";
                    //var_dump($mergeStr);

                }

                $sql =" insert into [@Auto_Import]  (" .implode(',', array_keys($targetData) ) .") values $mergeStr";
                //echo $sql;
                //die();
                $sql= mb_convert_encoding($sql, "GBK", "UTF-8");
                $result = $db->saveBysql($sql);

                $db->close();

                if ($result)
                    $this->assign('importResult', 'YES');
                else
                    $this->assign('importResult', 'NO');

                $this->display('jiaohangorderexecute');

            }


        }





    }

    public function pufaorderupload()
    {
        $this->display();
    }
    public function pufaorderexecute(){
        $time =time();

        // excel表头 与 SAP的对应关系
        $orderHeadArray = array(

            '浦发订单号' =>'U_OrderId', //A
            //'兑换流水' =>'?', //B
            '客户姓名'=>'U_Cstname', //C
            '礼品编号'=>'U_CitemCd', //D
            '礼品名称'=>'U_CitemNm', //E

            '兑换数量' =>'U_Qty', //F
            '派送地址' =>'U_Address', //G
            '邮政编码'=>'U_zipcode', //H
            //'公司电话'=>'?', //I
            //'家庭电话'=>'?', //J

            '移动电话' =>'U_Phone', //K
            '数据产生时间' =>'U_DocDate', //L
            //'配送状态'=>'?', //M
            //'物流公司'=>'?', //N
            //'物流编号'=>'?', //O

            //'供应商订单号' =>'?', //P
            //'出货日期' =>'?', //Q
            //'签收时间'=>'?', //R
            //'配送结果'=>'?', //S
            //'撤销日期'=>'?', //T

            //'撤销原因' =>'?', //U
            '备注' =>'U_Memo', //V
            '单价'=>'U_Price', //W
            '总价'=>'U_Total', //X
            '颜色'=>'U_Color', //Y

        );

        $html = "";
        $errorlist = array();
        $echoStr = '';
        $cellIndex = 5;
        ini_set("max_execution_time", "1800");
        import("@.ORG.Util.Sqlserver");
        $db = new Sqlserver();
        //Change to PDO_DBLIB
        //$db = new PDO_DBLIB_MSSQL();
        if (!empty($_FILES)) {
            import("@.ORG.UploadFile");
            $config=array(
                'allowExts'=>array('xlsx','xls'),
                'savePath'=>'./exceltojh/',
                'saveRule'=>'time',
            );
            $upload = new UploadFile($config);
            if (!$upload->upload($config['savePath'])) {
                $this->error($upload->getErrorMsg());
            } else {
                $is_sign = 0;
                $info = $upload->getUploadFileInfo();
                $name = $info[0]['savename'];
                Vendor('Excel.PHPExcel');
                $filename= $config['savePath'].$name;
                // echo $filename;exit;
                //导入thinkphp第三方类库
                $objPHPExcel = \PHPExcel_IOFactory::load($filename);

                $sheetData   = $objPHPExcel -> getActiveSheet() -> toArray(null, true, true, true);

                $currentSheet = $objPHPExcel->getSheet(0);
                //echo $currentSheet;exit;
                $allColumn = $currentSheet->getHighestColumn();//取到最大列数
                $allRow = $currentSheet->getHighestRow();//取到最大行数
                //echo $allRow;exit;

                // excel 中表头
                $excelHeadCN = $sheetData[1];
                $excelHead = array();
                foreach ($excelHeadCN as $key => $value){
                    //$excelHead[$orderHeadArray[$value]] = $key;
                    $excelHead[$key] = $orderHeadArray[$value];
                }
                unset($excelHead['']);
                foreach ($excelHead as $key => $value)
                {
                    if (empty($value)){
                        unset($excelHead[$key]);
                    }
                }
                // SAP表头与Excel列对应关系
                //var_dump($excelHead);

                unset($sheetData[1]); //删除excel表头 列名等行数据

                $mergeStr = '';
                $countNum = 0;

                foreach ($sheetData as $key => $v) {
                    //数据 $key行号 $v数组

                    $targetData = array();
                    foreach ($v as $key => $value)
                    {
                        $targetData[$excelHead[$key]] = trim($value);
                    }
                    unset($targetData['']);

                    // 补全数据
                    $targetData['U_CardCode'] = "C20013";
                    $targetData['U_Bat'] = $time;
                    $targetData['U_InptCode'] = "T007";

                    //convert to string
                    $str = "'".implode("','", $targetData)."'";

                    $countNum++;

                    if ($countNum == 1) $mergeStr .= "({$str})";
                    else $mergeStr .= ", ({$str})";
                    //var_dump($mergeStr);

                }

                $sql =" insert into [@Auto_Import]  (" .implode(',', array_keys($targetData) ) .") values $mergeStr";
                //echo $sql;
                //die();
                $sql= mb_convert_encoding($sql, "GBK", "UTF-8");
                $result = $db->saveBysql($sql);

                $db->close();

                if ($result)
                    $this->assign('importResult', 'YES');
                else
                    $this->assign('importResult', 'NO');

                $this->display('pufaorderexecute');

            }


        }

    }

    // 2017-12-04 OA中创建平台
    /**
     * @description: 查询平台
     */
    public function platformstatecheck()
    {
        $this->assign('src', 'SapSupplier/platformstatecheckiframe');
        $this->display();
    }

    function getPlatformListData()
    {
        $c_name = I('c_name');
        $eq_type = I('eq_type');

        $model = M('Platform');
        $pageIndex = I('pageIndex'); //? intval(I('pageIndex')) - 1 : 0;
        $pageSize = I('pageSize') ?: 50;
        //echo $pageIndex;
        $where = '1 = 1 ';
        if ($c_name) $where .= " AND p_name like '%{$c_name}%' ";

        if ($eq_type == 'all') {
        } else {


            if (!empty($eq_type)) {
                $where .= " AND examine_state = " . $eq_type . " ";
            } elseif ($eq_type == 0) {
                $where .= " AND examine_state = " . $eq_type . " ";
            }

        }

        //TODO:和当前用户绑定

        $operatorName = session("emp_no");

        $modelSupplierOperator = D("supplier_operator");
        $result = $modelSupplierOperator->where("emp_no='$operatorName'")->find();

        //if($result)
        if(1) {

            if ($result['type'] == 1) {
                // 审批人
            } else {
                // 发起人
                //$where .= " AND operatorid = " . $operator . " ";
            }

            $total = $model->where($where)->order("id desc")->count();
            $res = $model->where($where)->order("id desc")->limit($pageIndex * $pageSize, $pageSize)->select();

            echo json_encode(array('total' => $total, 'data' => $res));
            exit;

        }else{
            exit;
        }

    }

    /**
     * 新增 编辑 平台
     */
    function platformadd(){

        $this->display();

    }

    function getPlatformType()
    {
        $data = array(array('id'=>'1','name'=>'积分'),array('id'=>'2','name'=>'分期'),array('id'=>'4','name'=>'集采'));
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
        exit;
    }

    function getUserListsByRole()
    {
        $role = I('role');
        $salesSupervisorModel = M('salesSupervisor');
        $where = " 1=1 and the_role = {$role} ";
        $data = $salesSupervisorModel->where($where)->order('id asc')->select();
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
        exit;

    }

    function doplatformadd(){

        $respone = array('code'=>0,'msg'=>'保存成功');
        $saveData = json_decode($_POST['data'],true);

        $date = date('Y-m-d H:i:s');
        if(!$saveData){
            $respone['code']=-1;
            $respone['msg']='参数错误';
            echo json_encode($respone);exit;
        }
        $m = D('Platform');
        try {
            $id = $saveData['id'];
            unset($saveData['id']);
            if($id){
                // do update
                $saveData['gmt_modified'] = $date;
                $saveData['sync_sap']  = 'U';
                $saveData['examine_state'] = 0;
                $res =  $m->where("id={$id}")-> save($saveData);

                $remark = $saveData['p_remark'];
                $info = "修改了申请";
                $info = $remark?$info.",备注:".$remark:$info;
                $logModel =M('PlatformLog');
                $logModel->add(array('pid'=>$id,'user'=>session('user_name'),'info'=>$info,'ctime'=>date('Y-m-d H:i:s'),'type'=>__FUNCTION__));

            }else{
                //do save

                // 初始 card_code 为空
                $saveData['card_code'] = '';

                $saveData['sync_sap']  = 'A';
                $saveData['gmt_create'] = $date;
                $saveData['gmt_modified'] = $date;
                $saveData['operator_name'] = session('emp_no');

                $res =  $m->add($saveData);

                $remark = $saveData['p_remark'];
                $info = "发起申请";
                $info = $remark?$info.",备注:".$remark:$info;
                $logModel =M('PlatformLog');
                $logModel->add(array('pid'=>$res,'user'=>session('user_name'),'info'=>$info,'ctime'=>date('Y-m-d H:i:s'),'type'=>__FUNCTION__));

            }

            //TODO: 发送邮件
            //$receiver = "maxwell.shi";
            //$receiver = "wendy.li";
            //$operator = session('emp_no');
            //$this->sendEmail($receiver.'@g-town.com.cn', "平台:{$saveData['p_name']},信息变更", "平台:{$saveData['p_name']},信息变更<br/>操作人:{$operator}");

        }catch (\Exception $e){
            $respone['code']=-1;
            $respone['msg']=$e->getMessage();
            echo json_encode($respone);exit;
        }

        if(!$res){
            $respone['code']=-1;
            $respone['msg']=$m->getError();
        }

        echo json_encode($respone);exit;


    }

    function platformedit(){

        $id = intval(I('id'));
        if($id){
            $data = M('Platform')->where('id='.$id)->find();

            //check operatorid
            $authID = session('emp_no');
            if ($data['operator_name'] == $authID)
            {
                // can edit
                $this->assign('canedit',TRUE);
            }else{
                // can not
                $this->assign('canedit',FALSE);
            }

            //check permission
            if ($this->checkPermission()){
                // has permission,go progress then.
                $this->assign('haspermission',TRUE);
            }else{
                // has not permission.
                $this->assign('haspermission',FALSE);
            }

            $this->assign('data',$data);

            $this->display('platformedit');

        }

    }

    function getplatformlog(){
        $s_id   = intval(I('id'));
        $logModel =M('PlatformLog');
        $data = $logModel->where("pid={$s_id}")->order("id desc")->select();
        echo json_encode($data);
        exit;
    }

    public function review20171204()
    {

        if ($this->checkPermission()) {
            //platform ID
            $p_id = intval(I('id'));
            //审批类型
            $state = intval(I('state'));
            //审批记录表
            $logModel = M('PlatformLog');

            //platform 表
            $platformModel = M('Platform');
            //更新 platform 状态
            $platformModel->where("id={$p_id}")->save(array('examine_state' => $state));

            // 生成 card_code
            if($state == 1) {
                $platformItem = $platformModel->where("id={$p_id}")->find();
                if($platformItem['card_code'] == '')
                {

                    // create new card code
                    //$newCardCode = $this->generalCardCode();
                    $newCardCode = '';

                    // update database
                    $platformModel->where("id={$p_id}")->save(array('card_code' => $newCardCode));

                    // send out email
                    $data = $platformModel->where("id={$p_id}")->find();

                    //TODO: 发送邮件

                }
            }

            //记录审批历史
            $pRemark = I('p_remark');
            if ($state == 0) {
                $info = "发起申请";
            } else {
                $info = $state == 1 ? "审核通过" : "审核未通过";
            }
            $info = $pRemark ? $info . ",备注:" . $pRemark : $info;
            $logModel->add(array('pid' => $p_id, 'user' => session('user_name'), 'info' => $info, 'ctime' => date('Y-m-d H:i:s'), 'type' => __FUNCTION__));

            //返回数据
            echo 1;
            exit;
        }
        else{
            //返回数据
            echo 0;
            exit;
        }

    }

    function getPlatformCNType($type)
    {
        $cnType = '';
        switch ($type){
            case 1:
                $cnType = '积分';
                break;
            case 2:
                $cnType = '分期';
                break;
            case 4:
                $cnType = '集采';
                break;
            default:
                break;
        }
        return $cnType;

    }

    function generalCardCode()
    {

        $platformModel = M('Platform');
        $cardCodeArray = $platformModel->field('card_code')->group('card_code')->order('card_code desc')->limit(1)->find();
        $lastCardCode = $cardCodeArray['card_code'];
        $lastCardCodeNumber = substr($lastCardCode,2);
        $newCardCodeNumber = $lastCardCodeNumber + 1;
        $strlen = strlen($newCardCodeNumber);
        $totalLen = 4;
        $howManyToAdd = $totalLen - $strlen;
        $zeroString = '';
        for($i=1;$i<=$howManyToAdd;$i++){
            $zeroString .= '0';
        }
        $newCardCode = 'C2'.$zeroString.$newCardCodeNumber;
        return $newCardCode;

    }

    function sendCardCodeEmailBySAP()
    {
        // OA HOST/sapSupplier/sendCardCodeEmailBySAP/card_code/C20101,C20102
        $cardCodeString = I('card_code');
        //var_dump($cardCodeString);die();
        $cardCodeArray = explode(',',$cardCodeString);
        $sqlString = '';
        $tmpString = '';
        foreach ($cardCodeArray as $key => $item){
            $tmpString .= "'".$item."',";
        }
        $sqlString = substr($tmpString,0,strlen($tmpString)-1);
        $sqlString = '('.$sqlString.')';
        //var_dump($sqlString);die();

        // send out email
        $platformModel = M('Platform');
        $result = $platformModel->where("card_code in {$sqlString}")->select();
        //var_dump($result);die();

        $connent = "        
        <table align='center' border='1px' cellpadding='0px' cellspacing='0px' style='border-top: 0px solid #000000; border-left: 0px solid #000000; border-right: 0px solid #000000; border-bottom: 0px solid #000000;'>
        <tr>
            <td nowrap=\"nowrap\" align='center'>组长</td>
            <td nowrap=\"nowrap\" align='center'>经理/主管</td>
            <td nowrap=\"nowrap\" align='center'>专员</td>
            <td nowrap=\"nowrap\" align='center'>助理</td>
            <td nowrap=\"nowrap\" align='center'>性质</td>
            <td nowrap=\"nowrap\" align='center'>客户</td>
            
            <td nowrap=\"nowrap\" align='center'>CardCode</td>
            <td nowrap=\"nowrap\" align='center'>原命名</td>
            <td nowrap=\"nowrap\" align='center'>品牌数</td>
            <td nowrap=\"nowrap\" align='center'>品类数</td>
            <td nowrap=\"nowrap\" align='center'>SKU数</td>
            <td nowrap=\"nowrap\" align='center'>上线状态</td>
            
            <td nowrap=\"nowrap\" align='center'>备注</td>
        </tr>
        ";

        foreach ($result as $key => $data) {

            $connent .= "<tr>
            <td>" . $data['team_leader'] . "</td>
            <td>" . $data['team_manager'] . "</td>
            <td>" . $data['team_commissioner'] . "</td>
            <td>" . $data['team_assistant'] . "</td>
            <td>" . $this->getPlatformCNType($data['p_type']) . "</td>
            <td>" . $data['p_name'] . "</td>
            
            <td>" . $data['card_code'] . "</td>
            <td>" . $data['original_name'] . "</td>
            <td>" . $data['brand_count'] . "</td>
            <td>" . $data['category_count'] . "</td>
            <td>" . $data['sku_count'] . "</td>
            <td>" . $data['online_state'] . "</td>
            
            <td>" . $data['p_remark'] . "</td>
        </tr>";

        }

        $connent .= "</table>";

        if($result) {
            //TODO: 发送邮件
            //$receiver = "mktd@g-town.com.cn"; //市场部
            //$ccArray = array('wendy.li@g-town.com.cn','maxwell.shi@g-town.com.cn','austin@g-town.com.cn','tony@g-town.com.cn');
            // 市场部全体，抄送给Tony和wendy。:
            $receiver = "austin@g-town.com.cn";
            $ccArray = array('maxwell.shi@g-town.com.cn','molly.li@g-town.com.cn');
            $this->sendEmail($receiver, "新平台：" . $cardCodeString, $connent, '', $ccArray);
        }
        exit;
    }

    /**
     * 合成图片
     */
    function mergeimages(){

        $plugin['date'] = true;
        $plugin['uploader'] = true;
        $plugin['editor'] = true;
        $plugin['auth'] = true;

        $this -> assign("plugin", $plugin);
        $this->display();

    }

    function domergeimages(){

        $fontSize = 34;
        $fontWidth = 12;

        // get data
        $imgData = json_decode($_GET['data'],true);
        $imgArray = explode(',',$imgData['logo']);
        $imgUrl = parse_url($imgArray[0])['path'];
        $originalImage = substr($imgUrl,1);
        $waterMarkText = $imgData['waterMarkText'];
        $textLen = strlen($waterMarkText)*$fontWidth;
        $thePosition = $imgData['thePosition'];


        // merge images
        $manager = new ImageManager(array('driver' => 'GD'));
        $mainImage = $manager->make($originalImage);

        $px = 0;
        $py = 0;

        switch ($thePosition){
            case 'top-left':
                $px = 0;
                $py = 0;
                break;
            case 'top':
                $px = $mainImage->width()/2-$textLen/2;
                $py =0;
                break;
            case 'top-right':
                $px = $mainImage->width()-$textLen;
                $py =0;
                break;
            case 'center-left':
                $px = 0;
                $py = $mainImage->height()/2;
                break;
            case 'center':
                $px = $mainImage->width()/2-$textLen/2;
                $py = $mainImage->height()/2;
                break;
            case 'center-right':
                $px = $mainImage->width()-$textLen;
                $py = $mainImage->height()/2;
                break;
            case 'bottom-left':
                $px = 0;
                $py = $mainImage->height()-$fontSize;
                break;
            case 'bottom':
                $px = $mainImage->width()/2-$textLen/2;
                $py = $mainImage->height()-$fontSize;
                break;
            case 'bottom-right':
                $px = $mainImage->width()-$textLen;
                $py = $mainImage->height()-$fontSize;
                break;
        }

        // $fontSize=34
        $mainImage->text($waterMarkText,$px,$py,function($font) {
            $font->file('fonts/simkai.ttf');
            $font->size(34);
            $font->color('#000000');
            $font->align('left');
            $font->valign('top');
//            $font->angle(45);
        });

        $targetImage = $originalImage.'_'.uniqid().'.jpg';
        $mainImage->save($targetImage);

        echo $targetImage;

        exit();

    }

}